黑马程序员技术交流社区
标题:
问大家一下,记住密码和自动登录是怎么实现的呀
[打印本页]
作者:
赵永生
时间:
2014-2-23 11:47
标题:
问大家一下,记住密码和自动登录是怎么实现的呀
如题,求思路和代码。
作者:
轩辕冰晨
时间:
2014-2-23 12:03
实现这个功能关键就是服务端要识别客户的身份。而用Cookie是最简单的身从验证。当然浏览器不能禁用了,
如果用户第一次登录,可以将用户名作为Cookie写到本地。代码
Cookie cookie = new Cookie("user", zhangsan);//保存用户名
cookie.setMaxAge(365 * 24 * 3600);//保存时间
cookie.setPath("/");
response.addCookie(cookie);
当用户再次访问程序时,服务端程序应该检测这个Cookie是否存在,代码如下:
Cookie[] cookies=request.getCookies();
for(Cookie cookie: cookies)
{
if(cookie.getName().equals(user))
{
// 如果user Cookie存在,进行处理
break;
}
}
作者:
何清林
时间:
2014-2-23 14:22
原理:
登录时,把数据以[用户名:时间:密码:key:id]形式加密
其中密码与key是单项加密
自动登录时,首先使用id与用户名加载用户信息.
然后把查询出来的密码与key再次加密,与上次结果比较
如果两次加密相等,则登录成功
下面是代码:
日常记录,代码是根据SpringSecurity写的。
写个Entity类实现UserDetails
01
package com.lqz.b2c.base.web.controller.member.support;
02
03
import com.lqz.b2c.base.entity.Passport;
04
import com.lqz.base.auth.UsernameNotFoundException;
05
import com.lqz.base.auth.userdetails.UserDetails;
06
07
public class LoginUserSupport implements UserDetails {
08
09
private static final long serialVersionUID = 20130411151453L;
10
11
public LoginUserSupport() {
12
// TODO Auto-generated constructor stub
13
}
14
15
public LoginUserSupport(Passport passport) throws UsernameNotFoundException {
16
if (passport == null || passport.getId() == null
17
|| passport.getId() <= 0 || passport.getLoginName() == null
18
|| passport.getPassword() == null) {
19
throw new UsernameNotFoundException();
20
}
21
setId(passport.getId());
22
setUsername(passport.getLoginName());
23
setPassword(passport.getPassword());
24
}
25
26
private Long id;
27
private String username;
28
private String password;
29
30
public Long getId() {
31
return id;
32
}
33
34
public void setId(Long id) {
35
this.id = id;
36
}
37
38
public String getUsername() {
39
return username;
40
}
41
42
public void setUsername(String username) {
43
this.username = username;
44
}
45
46
public void setLoginName(String loginName) {
47
this.username = loginName;
48
}
49
50
public String getPassword() {
51
return password;
52
}
53
54
public void setPassword(String password) {
55
this.password = password;
56
}
57
58
/**
59
* 非过期账户
60
*/
61
@Override
62
public boolean isAccountNonExpired() {
63
return true;
64
}
65
66
@Override
67
public boolean isAccountNonLocked() {
68
return true;
69
}
70
71
@Override
72
public boolean isCredentialsNonExpired() {
73
return true;
74
}
75
76
@Override
77
public boolean isEnabled() {
78
return true;
79
}
80
81
}
写个处理类,继承UserDetailsService
01
package com.lqz.b2c.base.service.impl;
02
03
import javax.annotation.Resource;
04
05
import org.springframework.dao.DataAccessException;
06
import org.springframework.stereotype.Service;
07
import org.springframework.transaction.annotation.Transactional;
08
09
import com.lqz.b2c.base.entity.Passport;
10
import com.lqz.b2c.base.repository.IPassportDao;
11
import com.lqz.b2c.base.service.IPassportMgr;
12
import com.lqz.b2c.base.web.controller.member.support.LoginUserSupport;
13
import com.lqz.base.auth.UsernameNotFoundException;
14
import com.lqz.base.auth.userdetails.UserDetails;
15
import com.lqz.base.auth.userdetails.UserDetailsService;
16
17
/**
18
* @author 小败
19
*
20
*/
21
@Service("passportMgrImpl")
22
@Transactional(readOnly = true)
23
public class PassportMgrImpl implements IPassportMgr, UserDetailsService {
24
25
26
27
28
@Override
29
public UserDetails loadUser(Long userId, String username)
30
throws UsernameNotFoundException, DataAccessException {
31
Passport passport = passportDao.findByIDAndLoginName(userId, username);
32
LoginUserSupport user = new LoginUserSupport(passport);
33
return user;
34
}
35
36
37
38
/** 注入 **/
39
40
private IPassportDao passportDao;
41
42
@Resource(name = "passportDao")
43
public void setPassportDao(IPassportDao passportDao) {
44
this.passportDao = passportDao;
45
}
46
47
}
登录处使用
01
@RequestMapping(method = RequestMethod.POST)
02
public String login(LoginUserSupport user, HttpServletRequest request,
03
HttpServletResponse response, RedirectAttributes redirectAttributes) {
04
Passport passport = passportMgr.login(user.getUsername(),
05
user.getPassword());
06
if (passport != null) {
07
user.setId(passport.getId());
08
user.setPassword(passport.getPassword());
09
rememberMeService.loginSuccess(request, response, user);
10
return passportMgr.login(request.getSession(), passport);
11
}
12
redirectAttributes.addFlashAttribute("login_error", "登录失败");
13
return "redirect:/login";
14
}
退出登录处理
1
public String logout(HttpServletRequest request,
2
HttpServletResponse response, HttpSession session) {
3
logger.info("LogoutController#logout");
4
rememberMeService.logout(request, response);
5
session.invalidate();
6
return "redirect:/";
7
}
拦截器自动登录实现
01
public boolean preHandle(HttpServletRequest request,
02
HttpServletResponse response, Object obj) throws Exception {
03
/**
04
* 判断用户有没有登录
05
*/
06
Passport account = (Passport) WebUtils.getSessionAttribute(request, "passport");
07
if (account != null) {
08
return true;
09
}
10
11
/**
12
* 判断有没有Cookie 有的话提取Cookie 内容
13
*/
14
UserDetails user = rememberMeService.autoLogin(request, response);
15
if (user == null) {
16
return true;
17
}
18
19
/**
20
* 自动登录
21
*/
22
Passport passport = passportMgr.getPassportById(user.getId());
23
if (passport != null) {
24
passportMgr.login(request.getSession(), passport);
25
} else {
26
rememberMeService.loginFail(request, response);
27
}
28
return true;
29
}
Spring 配置
view sourceprint?
1
<bean id="rememberMeService" class="com.lqz.base.auth.rememberme.TokenBasedRememberMeServices">
2
<property name="key" value="20130411192953"/>
3
<property name="domain" value=".lqz.com"/><!-- option -->
4
<property name="parameter" value="rememberMe"/><!-- defult: remember_me -->
5
<property name="userDetailsService" ref="passportMgrImpl"/>
6
</bean>
作者:
何清林
时间:
2014-2-23 14:26
上面的很乱,我再写一遍:
原理
登录时,把数据以[用户名:时间:密码:key:id]形式加密
其中密码与key是单项加密
自动登录时,首先使用id与用户名加载用户信息.
然后把查询出来的密码与key再次加密,与上次结果比较
如果两次加密相等,则登录成功
1写个Entity类实现UserDetails
package com.lqz.b2c.base.web.controller.member.support;
import com.lqz.b2c.base.entity.Passport;
import com.lqz.base.auth.UsernameNotFoundException;
import com.lqz.base.auth.userdetails.UserDetails;
public class LoginUserSupport implements UserDetails {
private static final long serialVersionUID = 20130411151453L;
public LoginUserSupport() {
// TODO Auto-generated constructor stub
}
public LoginUserSupport(Passport passport) throws UsernameNotFoundException {
if (passport == null || passport.getId() == null
|| passport.getId() <= 0 || passport.getLoginName() == null
|| passport.getPassword() == null) {
throw new UsernameNotFoundException();
}
setId(passport.getId());
setUsername(passport.getLoginName());
setPassword(passport.getPassword());
}
private Long id;
private String username;
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public void setLoginName(String loginName) {
this.username = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/**
* 非过期账户
*/
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
写个处理类,继承UserDetailsService
package com.lqz.b2c.base.service.impl;
import javax.annotation.Resource;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lqz.b2c.base.entity.Passport;
import com.lqz.b2c.base.repository.IPassportDao;
import com.lqz.b2c.base.service.IPassportMgr;
import com.lqz.b2c.base.web.controller.member.support.LoginUserSupport;
import com.lqz.base.auth.UsernameNotFoundException;
import com.lqz.base.auth.userdetails.UserDetails;
import com.lqz.base.auth.userdetails.UserDetailsService;
/**
* @author 小败
*
*/
@Service("passportMgrImpl")
@Transactional(readOnly = true)
public class PassportMgrImpl implements IPassportMgr, UserDetailsService {
@Override
public UserDetails loadUser(Long userId, String username)
throws UsernameNotFoundException, DataAccessException {
Passport passport = passportDao.findByIDAndLoginName(userId, username);
LoginUserSupport user = new LoginUserSupport(passport);
return user;
}
/** 注入 **/
private IPassportDao passportDao;
@Resource(name = "passportDao")
public void setPassportDao(IPassportDao passportDao) {
this.passportDao = passportDao;
}
}
3:登录处使用:
@RequestMapping(method = RequestMethod.POST)
public String login(LoginUserSupport user, HttpServletRequest request,
HttpServletResponse response, RedirectAttributes redirectAttributes) {
Passport passport = passportMgr.login(user.getUsername(),
user.getPassword());
if (passport != null) {
user.setId(passport.getId());
user.setPassword(passport.getPassword());
rememberMeService.loginSuccess(request, response, user);
return passportMgr.login(request.getSession(), passport);
}
redirectAttributes.addFlashAttribute("login_error", "登录失败");
return "redirect:/login";
}
4 退出登录处理
public String logout(HttpServletRequest request,
HttpServletResponse response, HttpSession session) {
logger.info("LogoutController#logout");
rememberMeService.logout(request, response);
session.invalidate();
return "redirect:/";
}
5 拦截器自动登录实现
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object obj) throws Exception {
/**
* 判断用户有没有登录
*/
Passport account = (Passport) WebUtils.getSessionAttribute(request, "passport");
if (account != null) {
return true;
}
/**
* 判断有没有Cookie 有的话提取Cookie 内容
*/
UserDetails user = rememberMeService.autoLogin(request, response);
if (user == null) {
return true;
}
/**
* 自动登录
*/
Passport passport = passportMgr.getPassportById(user.getId());
if (passport != null) {
passportMgr.login(request.getSession(), passport);
} else {
rememberMeService.loginFail(request, response);
}
return true;
}
6 Spring 配置
<bean id="rememberMeService" class="com.lqz.base.auth.rememberme.TokenBasedRememberMeServices">
<property name="key" value="20130411192953"/>
<property name="domain" value=".lqz.com"/><!-- option -->
<property name="parameter" value="rememberMe"/><!-- defult: remember_me -->
<property name="userDetailsService" ref="passportMgrImpl"/>
</bean>
作者:
毛羚杨
时间:
2014-2-23 18:06
轩辕冰晨 发表于 2014-2-23 12:03
实现这个功能关键就是服务端要识别客户的身份。而用Cookie是最简单的身从验证。当然浏览器不能禁用了,
如 ...
学习了 cookie这个我还了解的不多哦
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2