使用Spring Security出现spring security Could not verify the provided CSRF token 异常

异常:Could not verify the provided CSRF token because your session was not found.

 

本项目是SpringBoot项目,模板引擎是thymeleaf

pom文件中 主要依赖为:

 

 
  1. <parent>

  2. <groupId>org.springframework.boot</groupId>

  3. <artifactId>spring-boot-starter-parent</artifactId>

  4. <version>1.5.9.RELEASE</version>

  5. <relativePath/> <!-- lookup parent from repository -->

  6. </parent>

  7.  
  8. <properties>

  9. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

  10. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

  11. <java.version>1.8</java.version>

  12. </properties>

  13.  
  14. <dependencies>

  15. <dependency>

  16. <groupId>org.springframework.boot</groupId>

  17. <artifactId>spring-boot-starter-data-jpa</artifactId>

  18. </dependency>

  19. <dependency>

  20. <groupId>org.springframework.boot</groupId>

  21. <artifactId>spring-boot-starter-data-redis</artifactId>

  22. </dependency>

  23. <dependency>

  24. <groupId>org.springframework.boot</groupId>

  25. <artifactId>spring-boot-starter-thymeleaf</artifactId>

  26. </dependency>

  27. <dependency>

  28. <groupId>org.springframework.boot</groupId>

  29. <artifactId>spring-boot-starter-web</artifactId>

  30. </dependency>

  31.  
  32. <!--security-->

  33. <dependency>

  34. <groupId>org.springframework.boot</groupId>

  35. <artifactId>spring-boot-starter-security</artifactId>

  36. </dependency>

  37.  
  38. <!-- 模板引擎-->

  39. <dependency>

  40. <groupId>org.springframework.boot</groupId>

  41. <artifactId>spring-boot-starter-thymeleaf</artifactId>

  42. </dependency>

  43.  
  44. <dependency>

  45. <groupId>mysql</groupId>

  46. <artifactId>mysql-connector-java</artifactId>

  47. <scope>runtime</scope>

  48. </dependency>

  49. <dependency>

  50. <groupId>org.projectlombok</groupId>

  51. <artifactId>lombok</artifactId>

  52. <optional>true</optional>

  53. </dependency>

  54. <dependency>

  55. <groupId>org.springframework.boot</groupId>

  56. <artifactId>spring-boot-starter-test</artifactId>

  57. <scope>test</scope>

  58. </dependency>

  59.  
  60. </dependencies>

 

 

原因:

Spring Security4默认是开启CSRF的,所以需要请求中包含CSRF的token信息,在其官方文档(参考资料1)中,提供了在form中嵌入一个hidden标签来获取token信息,其原理是,hidden标签使用了Spring Security4提供的标签,即${_csrf.parameterName}、${_csrf.token}, 后台页面渲染过程中,将此标签解所对应的值解析出来,这样,我们的form表单,就嵌入了Spring Security的所需的token信息,在后续的提交登录请求时,就不会出现没有CSRF token的异常。

另外,还有一个解决办法是,通过关闭CSRF来解决,这个几乎在任何场景中都能解决这个问题(上面这个解决方案,可能在某些渲染模板不能解析出来token值,不过可以通过后台程序来获取token值,然后自己定义变量来渲染到form中,这个也是可以的)。具体的做法是通过修改配置文件来关闭,我这里使用的是SpringBoot开发的项目,配置文件直接写在配置类中,通过.csrf().disable()来关闭,参考资料见二。不过这种方案,会迎来CSRF攻击,不建议在生产环境中使用,如果系统对外界做了隔离,这样做也是可以的。

 

解决办法:

1、在from表单中加入一个hidden标签,来引用spring security  的csrf token。

 

<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>

 

如果是jsp做模板引擎,则可以使用:

 

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

2、通过关闭csrf来解决:

 

 
  1. @Configuration

  2. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {//1

  3.  
  4. @Bean

  5. UserDetailsService customUserService() { //2

  6. return new UserService();

  7. }

  8.  
  9. // 配置登陆校验,登陆成功后,会保存session

  10. @Override

  11. protected void configure(AuthenticationManagerBuilder auth) throws Exception {

  12. auth.userDetailsService(customUserService()); //3

  13.  
  14. }

  15.  
  16. // 配置默认登陆页面,登陆失败页面

  17. @Override

  18. protected void configure(HttpSecurity http) throws Exception {

  19. http.authorizeRequests()

  20. .anyRequest().authenticated()

  21. .and()

  22. .csrf().disable() //关闭CSRF

  23. .formLogin()

  24. .loginPage("/login")

  25. .failureUrl("/login?error")

  26. .permitAll()

  27. .and()

  28. .logout().permitAll();

  29.  
  30. }

  31.  
  32.  
  33. }

Spring Security 6提供了强大的身份验证和授权功能,但集成验证码通常是为了增强安全性,防止恶意机器人的自动化登录尝试。在Spring Security中集成验证码可以通过以下步骤进行: 1. 添加依赖:首先,你需要在你的项目中添加验证码库,如Apache Commons Codec或Google Charts。Spring Security本身并不包含验证码功能,所以需要外部库支持。 ```xml <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> </dependency> <dependency> <groupId>com.google.code.kaptcha</groupId> <artifactId>kaptcha</artifactId> </dependency> ``` 2. 配置Kaptcha组件:配置Kaptcha的bean,设置验证码生成器、存储策略和拦截器。 ```java @Bean public KaptchaService kaptchaService() { KaptchaService kaptcha = new DefaultKaptcha(); kaptcha.setUrlBase("http://your-domain.com/kaptcha"); // 验证码图片URL前缀 kaptcha.setConfig(new KaptchaConfig()); return kaptcha; } @Bean public CaptchaFilter captchaFilter(KaptchaService kaptchaService) { CaptchaFilter captchaFilter = new CaptchaFilter(kaptchaService); captchaFilter.setUsernameAttribute("username"); // 用户名字段 return captchaFilter; } ``` 3. 配置SecurityWebApplicationInitializer:确保验证码拦截器在Spring Security的过滤链中正确放置。这通常在`configure(HttpSecurity http)`方法中完成。 ```java http .formLogin() .and() .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class); // 在用户名密码认证之前添加验证码过滤器 ``` 4. 更新登录表单:在前端HTML模板中,添加用于显示验证码和接收输入的表单元素。使用`<kaptcha:html>`标签展示验证码图片。 5. 处理验证码:在处理用户登录请求的后端控制器方法中,检查提交的验证码是否正确。 ```java @PostMapping("/login") public String login(@RequestParam String username, @RequestParam String password, @RequestParam String captcha) { if (!kaptchaService.verify(captcha)) { return "redirect:/login?error=invalid-captcha"; // 验证码错误重定向 } // ...继续验证密码和其他信息 } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值