SpringSecurity实现记住我功能
⒈表单添加
1 <form action="/authentication/form" method="post"> 2 <table> 3 <tr> 4 <td>用户名:</td> 5 <td><input id="username" type="text" name="username"></td> 6 </tr> 7 <tr> 8 <td>密码:</td> 9 <td><input id="password" type="password" name="password"></td> 10 </tr> 11 <tr> 12 <td>图形验证码:</td> 13 <td> 14 <input type="text" name="imageCode"> 15 <img src="/code/image"> 16 </td> 17 </tr> 18 <tr> 19 <td colspan="2"><input name="remember-me" type="checkbox" value="true"/>记住我</td> 20 </tr> 21 <tr> 22 <td colspan="2"><button type="submit">登录</button></td> 23 </tr> 24 </table> 25 </form>
⒉
1 @Autowired 2 private UserDetailsService userDetailsService; 3 4 @Bean 5 private DataSource dataSource; 6 7 @Bean 8 public PersistentTokenRepository persistentTokenRepository(){ 9 JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl(); 10 tokenRepository.setDataSource(dataSource); 11 tokenRepository.setCreateTableOnStartup(true); //系统在启动的时候生成“记住我”的数据表(只能使用一次) 12 return tokenRepository; 13 } 14 @Override 15 protected void configure(HttpSecurity http) throws Exception { 16 ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter(); 17 validateCodeFilter.setAuthenticationFailureHandler(coreqiAuthenticationFailureHandler); 18 19 //http.httpBasic() //httpBasic登录 BasicAuthenticationFilter 20 http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) //加载用户名密码过滤器的前面 21 .formLogin() //表单登录 UsernamePasswordAuthenticationFilter 22 .loginPage("/coreqi-signIn.html") //指定登录页面 23 //.loginPage("/authentication/require") 24 .loginProcessingUrl("/authentication/form") //指定表单提交的地址用于替换UsernamePasswordAuthenticationFilter默认的提交地址 25 .successHandler(coreqiAuthenticationSuccessHandler) //登录成功以后要用我们自定义的登录成功处理器,不用Spring默认的。 26 .failureHandler(coreqiAuthenticationFailureHandler) //自己体会把 27 .and() 28 .rememberMe() //对记住我进行设置 29 .tokenRepository(persistentTokenRepository()) 30 .tokenValiditySeconds(1000) //设置Token的有效时间 31 .userDetailsService(userDetailsService) //使用userDetailsService用Token从数据库中获取用户自动登录 32 .and() 33 .authorizeRequests() //对授权请求进行配置 34 .antMatchers("/coreqi-signIn.html","/code/image").permitAll() //指定登录页面不需要身份认证 35 .anyRequest().authenticated() //任何请求都需要身份认证 36 .and().csrf().disable(); //禁用CSRF 37 //FilterSecurityInterceptor 整个SpringSecurity过滤器链的最后一环 38 }