SpringSecurity实现记住我功能-LMLPHP

SpringSecurity实现记住我功能-LMLPHP

⒈表单添加

     <form action="/authentication/form" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input id="username" type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input id="password" type="password" name="password"></td>
</tr>
<tr>
<td>图形验证码:</td>
<td>
<input type="text" name="imageCode">
<img src="/code/image">
</td>
</tr>
<tr>
<td colspan="2"><input name="remember-me" type="checkbox" value="true"/>记住我</td>
</tr>
<tr>
<td colspan="2"><button type="submit">登录</button></td>
</tr>
</table>
</form>

     @Autowired
private UserDetailsService userDetailsService; @Bean
private DataSource dataSource; @Bean
public PersistentTokenRepository persistentTokenRepository(){
JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
tokenRepository.setDataSource(dataSource);
tokenRepository.setCreateTableOnStartup(true); //系统在启动的时候生成“记住我”的数据表(只能使用一次)
return tokenRepository;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
validateCodeFilter.setAuthenticationFailureHandler(coreqiAuthenticationFailureHandler); //http.httpBasic() //httpBasic登录 BasicAuthenticationFilter
http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) //加载用户名密码过滤器的前面
.formLogin() //表单登录 UsernamePasswordAuthenticationFilter
.loginPage("/coreqi-signIn.html") //指定登录页面
//.loginPage("/authentication/require")
.loginProcessingUrl("/authentication/form") //指定表单提交的地址用于替换UsernamePasswordAuthenticationFilter默认的提交地址
.successHandler(coreqiAuthenticationSuccessHandler) //登录成功以后要用我们自定义的登录成功处理器,不用Spring默认的。
.failureHandler(coreqiAuthenticationFailureHandler) //自己体会把
.and()
.rememberMe() //对记住我进行设置
.tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(1000) //设置Token的有效时间
.userDetailsService(userDetailsService) //使用userDetailsService用Token从数据库中获取用户自动登录
.and()
.authorizeRequests() //对授权请求进行配置
.antMatchers("/coreqi-signIn.html","/code/image").permitAll() //指定登录页面不需要身份认证
.anyRequest().authenticated() //任何请求都需要身份认证
.and().csrf().disable(); //禁用CSRF
//FilterSecurityInterceptor 整个SpringSecurity过滤器链的最后一环
}
05-11 01:15