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 }
作者:奇
出处:https://www.cnblogs.com/fanqisoft/p/10630631.html
版权:本作品采用「本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。」许可协议进行许可。
分类:
Spring Security
如果文章内容对您有所帮助,欢迎赞赏.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!