使用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. org.springframework.boot

  2. spring-boot-starter-parent

  3. 1.5.9.RELEASE

  4.  
  5. UTF-8

  6. UTF-8

  7. 1.8

  8.  
  9. org.springframework.boot

  10. spring-boot-starter-data-jpa

  11. org.springframework.boot

  12. spring-boot-starter-data-redis

  13. org.springframework.boot

  14. spring-boot-starter-thymeleaf

  15. org.springframework.boot

  16. spring-boot-starter-web

  17.  
  18. org.springframework.boot

  19. spring-boot-starter-security

  20.  
  21. org.springframework.boot

  22. spring-boot-starter-thymeleaf

  23.  
  24. mysql

  25. mysql-connector-java

  26. runtime

  27. org.projectlombok

  28. lombok

  29. true

  30. org.springframework.boot

  31. spring-boot-starter-test

  32. test

  33.  

 

 

原因:

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。

 

 

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

 

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出现spring security Could not verify the provided CSRF token 异常)