RememberMeAuthenticationFilter的作用是, 当用户没有登录而直接访问资源时, 从cookie里找出用户的信息, 如果Spring Security能够识别出用户提供的remember me cookie, 用户将不必填写用户名和密码, 而是直接登录进入系统. 它先分析SecurityContext里有没有Authentication对象. 如果有, 则不做任何操作, 直接跳到下一个过滤器. 如果没有, 则检查request里有没有包含remember-me的cookie信息. 如果有, 则解析出cookie里的验证信息, 判断是否有权限.
它的基本配置如下:
<sec:http entry-point-ref="myAuthenticationEntryPoint">
...
<sec:custom-filter ref="rememberMeFilter" position="REMEMBER_ME_FILTER"/>
</sec:http>
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider ref="authenticationProvider"/>
<sec:authentication-provider ref="rememberMeAuthenticationProvider"/>
</sec:authentication-manager>
<bean id="loginAuthenticationFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
...
<property name="rememberMeServices" ref="tokenBasedRememberMeServices"></property>
</bean>
<bean id="rememberMeAuthenticationProvider" class="org.springframework.security.authentication.RememberMeAuthenticationProvider">
<property name="key" value="000016aad72443b3b78af239a0b6bd7c"/>
</bean>
<bean id="rememberMeFilter" class="org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager"></property>
<property name="rememberMeServices" ref="tokenBasedRememberMeServices"></property>
</bean>
<bean id="tokenBasedRememberMeServices" class="org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
<property name="key" value="000016aad72443b3b78af239a0b6bd7c"></property>
<property name="userDetailsService" ref="userService"></property>
</bean>
注意几点:
1) 在authenticationManager里要加多一个authentication provider -- RememberMeAuthenticationProvider;
2) 要为UsernamePasswordAuthenticationFilter的rememberMeServices属性指定一个实例;
3) RememberMeAuthenticationProvider和TokenBasedRememberMeServices都要为它们的key属性指定一个唯一的值. 这个值可以用应用名加一个不少于36位长度的随机字符串. 这个key是用来识别当前应用的唯一值.
4) 在提交登录表单的时候, 一定要加多一个名的_spring_security_remember_me的参数(这个名字可以改), 值可以是"true", "yes", "on"或"1". 如下:
<form id="loginForm" method="POST" action="my_login">
姓名: <input type="text" id="my_username" name="my_username"/><br>
密码: <input type="password" id="my_password" name="my_password"/>
<input type="button" value="登录" οnclick="login()"/><br>
<input id="_spring_security_remember_me" name="_spring_security_remember_me" type="checkbox" value="true"/>
<label for="_spring_security_remember_me">Remember Me?</label>
</form>
在Spring Security的过滤器链里, RememberMeAuthenticationFilter是排在UsernamePasswordAuthenticationFilter之后的. 在第一次登录时(如果勾选了remember me), 在验证信息正确后, AbstractAuthenticationProcessingFilter(UsernamePasswordAuthenticationFilter的父类)最后会调用一个叫successfulAuthentication()的方法:
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
Authentication authResult) throws IOException, ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Authentication success. Updating SecurityContextHolder to contain: " + authResult);
}
SecurityContextHolder.getContext().setAuthentication(authResult);
// 调用rememberMeServices的loginSuccess()方法.
rememberMeServices.loginSuccess(request, response, authResult);
// Fire event
if (this.eventPublisher != null) {
eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass()));
}
successHandler.onAuthenticationSuccess(request, response, authResult);
}
这个方法会调用rememberMeService的loginSuccess()方法(所以之前我们要在配置文件了为UsernamePasswordAuthenticationFilter配上它的rememberMeService实例). loginSuccess()方法最后会调用onLoginSuccess()方法. 上面我们配置的rememberMeService的实例是TokenBasedRememberMeServices. 现在我们看看它的onLoginSuccess()方法:
public void onLoginSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication successfulAuthentication) {
String username = retrieveUserName(successfulAuthentication);
String password = retrievePassword(successfulAuthentication);
// If unable to find a username and password, just abort as TokenBasedRememberMeServices is
// unable to construct a valid token in this case.
if (!StringUtils.hasLength(username)) {
logger.debug("Unable to retrieve username");
return;
}
if (!StringUtils.hasLength(password)) {
UserDetails user = getUserDetailsService().loadUserByUsername(username);
password = user.getPassword();
if (!StringUtils.hasLength(password)) {
logger.debug("Unable to obtain password for user: " + username);
return;
}
}
int tokenLifetime = calculateLoginLifetime(request, successfulAuthentication);
long expiryTime = System.currentTimeMillis();
// SEC-949
expiryTime += 1000L* (tokenLifetime < 0 ? TWO_WEEKS_S : tokenLifetime);
// 把用户名, cookie的过期时间, 登录密码和key组成一个字符串, 然后用MD5加密
String signatureValue = makeTokenSignature(expiryTime, username, password);
// 把加密字符串放进cookie里, 然后返回给浏览器
setCookie(new String[] {username, Long.toString(expiryTime), signatureValue}, tokenLifetime, request, response);
if (logger.isDebugEnabled()) {
logger.debug("Added remember-me cookie for user '" + username + "', expiry: '"
+ new Date(expiryTime) + "'");
}
}
这个方法主设置了一个cookie在用户的浏览器上, 它包含一个Base64编码的字符串, 包含以下内容:
- 用户的名字;
- 过期的日期/时间;
- 一个MD5的加密字符串, 包括过期日期/时间, 用户名和密码;
- 应用的key值, 是在TokenBasedRememberMeServices实例的key属性中定义的.
此时, 在登录成功后, 我们可以从浏览器里看到返回的信息里多了一个名为SPRING_SECURITY_REMEMBER_ME_COOKIE的cookie信息.
在后面的每个请求里面, request对象里都会附上这个cookie信息,
即使我们登出了, 这个cookie信息还会继续存在,
接着, 如果我们不登录, 而是直接访问页面的话, 它会访问成功. 因为这个时候, RememberMeAuthenticationFilter过滤器将会检查cookie的内容并通过检查是否为一个认证过的remember-me cookie来认证用户.
RememberMeAuthenticationFilter的doFilter()方法如下:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
// 如果SecurityContext里没有包含Authentication对象
if (SecurityContextHolder.getContext().getAuthentication() == null) {
// 从request里解析出SPRING_SECURITY_REMEMBER_ME_COOKIE的信息, 然后转成一个RememberMeAuthenticationToken对象
Authentication rememberMeAuth = rememberMeServices.autoLogin(request, response);
if (rememberMeAuth != null) {
// Attempt authenticaton via AuthenticationManager
try {
// 再判断rememberMeAuth对象里的key值是否与配置文件里的key值相同
rememberMeAuth = authenticationManager.authenticate(rememberMeAuth);
// Store to SecurityContextHolder
SecurityContextHolder.getContext().setAuthentication(rememberMeAuth);
onSuccessfulAuthentication(request, response, rememberMeAuth);
if (logger.isDebugEnabled()) {
logger.debug("SecurityContextHolder populated with remember-me token: '"
+ SecurityContextHolder.getContext().getAuthentication() + "'");
}
// Fire event
if (this.eventPublisher != null) {
eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(
SecurityContextHolder.getContext().getAuthentication(), this.getClass()));
}
if (successHandler != null) {
successHandler.onAuthenticationSuccess(request, response, rememberMeAuth);
return;
}
} catch (AuthenticationException authenticationException) {
if (logger.isDebugEnabled()) {
logger.debug("SecurityContextHolder not populated with remember-me token, as "
+ "AuthenticationManager rejected Authentication returned by RememberMeServices: '"
+ rememberMeAuth + "'; invalidating remember-me token", authenticationException);
}
rememberMeServices.loginFail(request, response);
onUnsuccessfulAuthentication(request, response, authenticationException);
}
}
chain.doFilter(request, response);
} else {
if (logger.isDebugEnabled()) {
logger.debug("SecurityContextHolder not populated with remember-me token, as it already contained: '"
+ SecurityContextHolder.getContext().getAuthentication() + "'");
}
chain.doFilter(request, response);
}
}
它首先解析出cookie里的remember-me信息, 然后从数据库拿出用户的信息, 再比较两个信息是否一致, 来完成验证.
这里要注意 authenticationManager.authenticate(rememberMeAuth) 这个方法, 它会轮流调用authenticationManager里所有的AuthenticationProvider来进行验证. 而只有RememberMeAuthenticationProvider才能验证remember-me信息, 所有上面的配置文件里, 我们要为authenticationManager配多一个authentication-provider的实例 -- RememberMeAuthenticationProvider.
---------------------------------------
浏览器里的cookie信息什么时候会消失:
1) cookie自动过期
2) 手动清除浏览器的cookie信息(关闭浏览器不会自动清除cookie)
3) 登录一次失败后, 之前cookie里的remember-me信息会消失. (这个估计是RequestCacheAwareFilter的原因, 具体原因以后再补充)