自动登录与注销登录
一、自动登录
自动登录实质上是指将用户的登录信息保存在用户浏览器cookie中,当用户下次访问时,自动实现校验并建立登录状态的一种机制。
处于安全考虑会将用户信息先加密,再存于cookie中。
Spring Security提供了两种非常好的令牌
- 用散列算法加密用户登录信息并生成令牌
- 数据库等持久性数据存储机制用的持久化令牌
1. 散列加密方案
修改配置configure()(基于过滤器实现图形验证码代码修改)
@Autowired
private MyUserDetailsService myUserDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/api/**").hasRole("ADMIN")
.antMatchers("/user/api/**").hasRole("USER")
.antMatchers("/app/api/**", "/captcha.jpg").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/myLogin.html")
// 指定处理登录请求的路径,修改请求的路径,默认为/login
.loginProcessingUrl("/mylogin").permitAll()
.failureHandler(new MyAuthenticationFailureHandler())
.and()
//增加自动登录功能,默认为散列加密
.rememberMe()
.userDetailsService(myUserDetailsService)
.key("autologin")
.and()
.csrf().disable();
// 将过滤器添加在UsernamePasswordAuthenticationFilter之前
http.addFilterBefore(new VerificationCodeFilter(), UsernamePasswordAuthenticationFilter.class);
}
在自定义页面中添加remember-me checkbox
注意: name必须为remember-me
<div>
<label>
<input name="remember-me" type="checkbox" value="true"> 记住我
</label>
</div>
启动项目
访问api:http://localhost:8080/user/api/hi
勾选记住我
登录
打开控制台查看cookie
在源码中可以找到与之对应代码
public abstract class AbstractRememberMeServices implements RememberMeServices, InitializingBean, LogoutHandler {
public static final String SPRING_SECURITY_REMEMBER_ME_COOKIE_KEY = "remember-me";
public static final String DEFAULT_PARAMETER = "remember-me";
public static final int TWO_WEEKS_S = 1209600;
private static final String DELIMITER = ":";
protected final Log logger = LogFactory.getLog(this.getClass());
protected final MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private UserDetailsService userDetailsService;
private UserDetailsChecker userDetailsChecker = new AccountStatusUserDetailsChecker();
private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource();
private String cookieName = "remember-me";
private String cookieDomain;
private String parameter = "remember-me";
private boolean alwaysRemember;
private String key;
private int tokenValiditySeconds = 1209600;
private Boolean useSecureCookie = null;
private GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper();
...
Spring Security每次登录成功之后会更新令牌
public void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
String username = this.retrieveUserName(successfulAuthentication);
String password = this.retrievePassword(successfulAuthentication);
if (!StringUtils.hasLength(username)) {
this.logger.debug("Unable to retrieve username");
} else {
if (!StringUtils.hasLength(password)) {
UserDetails user = this.getUserDetailsService().loadUserByUsername(username);
password = user.getPassword();
if (!StringUtils.hasLength(password)) {
this.logger.debug("Unable to obtain password for user: " + username);
return;
}
}
int tokenLifetime = this.calculateLoginLifetime(request, successfulAuthentication);
long expiryTime = System.currentTimeMillis();
expiryTime += 1000L * (long)(tokenLifetime < 0 ? 1209600 : tokenLifetime);
String signatureValue = this.makeTokenSignature(expiryTime, username, password);
this.setCookie(new String[]{username, Long.toString(expiryTime), signatureValue}, tokenLifetime, request, response);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Added remember-me cookie for user '" + username + "', expiry: '" + new Date(expiryTime) + "'");
}
}
}
加密部分
protected String makeTokenSignature(long tokenExpiryTime, String username, String password) {
String data = username + ":" + tokenExpiryTime + ":" + password + ":" + this.getKey();
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException var8) {
throw new IllegalStateException("No MD5 algorithm available!");
}
return new String(Hex.encode(digest.digest(data.getBytes())));
}
key默认情况下是随机生成的
private String getKey() {
if (this.key == null) {
if (this.rememberMeServices instanceof AbstractRememberMeServices) {
this.key = ((AbstractRememberMeServices) rememberMeServices).getKey();
} else {
this.key = UUID.randomUUID().toString();
}
}
return this.key;
}
这样会导致每次重启项目都会重新生成key,使之前浏览器保存的全部失效。
另外当多实例部署时由于实例之间的key都不相同,所以当访问另一个实例时自动登录策略也会失效
合理的做法是指定key
这种方式实现简单,无需花费服务器资源存储自动登录的相关信息。但是存在cookie被盗风险。
2. 持久化令牌方案
相比于散列加密方案采用了更加严谨的安全设计
核心的两个值(都是采用MD5加密过的随机字符串)
- series 仅在用户使用密码重新登录时更新
- token 在每一个新的session中都重新生成
这样做的的好处
- 解决了一个令牌在多端登录的情况
- 同时校验series和token,如果令牌被盗,当非法登录时,会刷新token的值,这样合法用户自动登录的时候,校验series一样,但是token不一样,可以推测令牌被盗用。
Spring Security使用PersistentRememberMeToken来表明一个验证实体
public class PersistentRememberMeToken {
private final String username;
private final String series;
private final String tokenValue;
//最后一次自动登录的时间
private final Date date;
...
}
在数据库中建一张persistent_logins表(存储自动登录信息的表)
CREATE TABLE `persistent_logins` (
`username` varchar(64) NOT NULL,
`series` varchar(64) NOT NULL,
`token` varchar(64) NOT NULL,
`last_used` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`series`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
定制tokenRepository
配置中需要传入一个PersistentTokenRepository实例,此接口定义了持久化令牌的一些必要方法
public interface PersistentTokenRepository {
void createNewToken(PersistentRememberMeToken var1);
void updateToken(String var1, String var2, Date var3);
PersistentRememberMeToken getTokenForSeries(String var1);
void removeUserTokens(String var1);
}
可以利用自带的实现类JdbcTokenRepositoryImpl实现持久化
为其指定DataSource
@Autowired
private DataSource dataSource;
@Autowired
private MyUserDetailsService myUserDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
http.authorizeRequests()
.antMatchers("/admin/api/**").hasRole("ADMIN")
.antMatchers("/user/api/**").hasRole("USER")
.antMatchers("/app/api/**", "/captcha.jpg").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/myLogin.html")
// 指定处理登录请求的路径,修改请求的路径,默认为/login
.loginProcessingUrl("/mylogin").permitAll()
.failureHandler(new MyAuthenticationFailureHandler())
.and()
//增加自动登录功能,默认为散列加密
.rememberMe()
.userDetailsService(myUserDetailsService)
.tokenRepository(jdbcTokenRepository)
.and()
.csrf().disable();
// 将过滤器添加在UsernamePasswordAuthenticationFilter之前
http.addFilterBefore(new VerificationCodeFilter(), UsernamePasswordAuthenticationFilter.class);
}
启动项目
访问api:http://localhost:8080/user/api/hi
登录
查看表中自动插入了验证数据
重启项目
访问api:http://localhost:8080/user/api/hi
自动登录
和我们预料的一样,series不变,验证自动登录成功后刷新token的值
这种方式同样存在令牌被盗的风险
二、注销登录
1. 系统自带
Spring Security自带注销登录逻辑
默认请求 /logout
注销后
HttpSession失效、清空已配置的Remember-me验证,以及清空SecurityContextHolder
2.自行配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http.logout()
//指定接受注销请求的路径
.logoutUrl("/logout")
//注销成功,重定向到该路径下
.logoutSuccessUrl("/")
//注册成功之后处理方式
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
}
})
//使该用户的HttpSession失效
.invalidateHttpSession(true)
//注销成功,删除指定cookie
.deleteCookies("remember-me")
//用于注销的处理方式,允许自定义一些清理策略
.addLogoutHandler(new LogoutHandler() {
@Override
public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
}
});
}