RememberMeServices
public interface RememberMeServices { //当用用户进行到系统未登录是自动登录 Authentication autoLogin(HttpServletRequest request, HttpServletResponse response); //在用户登录失败的时候调用 void loginFail(HttpServletRequest request, HttpServletResponse response); //在用户登录成功后调用 void loginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication); }
AbstractRememberMeServices
1. loginSuccess : 在玩家登录成功后调用这个方法,首先通过rememberMeRequested这个方法判断是否需要rememberMe,若需要,那么调用抽象方法onLoginSuccess
2. loginFail : 在玩家登录失败后调用方法,首先执行cancelCookie删除cookie;然后执行方法onLoginFail
3. autoLogin : 首先从cookie中获取到加密后的字符串,然后解析这个加密字符串,调用抽象方法processAutoLoginCookie执行自动登录,最后返回一个完整的Authentication
TokenBasedRememberMeServices
1. onLoginSuccess : 完成加密 MD5 ("username:tokenExpiryTime:password:key"),设置加密字符串到cookie(详细加密查询makeTokenSignature方法)
2. processAutoLoginCookie:通过解析出来的用户名调用getUserDetailsService().loadUserByUsername(cookieTokens[0])查询出UserDetails,然后在加密查询出来的UserDetails,比较cookie中加密的字符串和查询出来的UserDetails加密字符串,若相同,完成自动登录
PersistentTokenBasedRememberMeServices
1. onLoginSuccess : 保存用户登录信息PersistentRememberMeToken到数据库和cookie(不会保存用户名到cookie,相对更安全)
2. processAutoLoginCookie : 通过解析出cookie中的数据,查询数据库中的PersistentRememberMeToken,检验查询出来的PersistentRememberMeToken是否过期,正确等等,最后查询出UserDetails,完成登录
3.对PersistentRememberMeToken做的数据库操作都是通过PersistentTokenRepository来完成的
TokenBasedRememberMeServices来实现的RememberMe
在项目的security.xml文件中添加如下代码:
<security:http> <security:intercept-url pattern="/**" access="ROLE_USER"/> <security:form-login/> <security:logout logout-url="/logout"/> <security:remember-me key="chapter4"/> </security:http>
PersistentTokenBasedRememberMeServices来实现RememberMe
1. 在数据库执行sql:
CREATE TABLE persistent_logins ( username VARCHAR(64) NOT NULL, series VARCHAR(64) PRIMARY KEY, token VARCHAR(64) NOT NULL, last_used TIMESTAMP NOT NULL );
2. 修改security.xml文件:
<security:http> <security:intercept-url pattern="/**" access="ROLE_USER"/> <security:form-login/> <security:logout logout-url="/logout"/> <security:remember-me data-source-ref="securityDataSource"/> </security:http>
这里可以配置token-repository-ref或者data-source-ref 效果都是一样
<security:http> <security:intercept-url pattern="/**" access="ROLE_USER"/> <security:form-login/> <security:logout logout-url="/logout"/> <security:remember-me token-repository-ref="jdbcTokenRepositoryImpl"/> </security:http> <bean id="jdbcTokenRepositoryImpl" class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl"> <property name="dataSource" ref="securityDataSource"/> </bean>