Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

前端 未结 11 2475
你的背包
你的背包 2020-12-07 15:38

After configuring Spring Security 3.2, _csrf.token is not bound to a request or a session object.

This is the spring security config:

&l         


        
相关标签:
11条回答
  • 2020-12-07 15:49

    With thymeleaf you may add:

    <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
    
    0 讨论(0)
  • 2020-12-07 15:50

    It looks like the CSRF (Cross Site Request Forgery) protection in your Spring application is enabled. Actually it is enabled by default.

    According to spring.io:

    When should you use CSRF protection? Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection.

    So to disable it:

    @Configuration
    public class RestSecurityConfig extends WebSecurityConfigurerAdapter {
      @Override
      protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
      }
    }
    

    If you want though to keep CSRF protection enabled then you have to include in your form the csrftoken. You can do it like this:

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

    You can even include the CSRF token in the form's action:

    <form action="./upload?${_csrf.parameterName}=${_csrf.token}" method="post" enctype="multipart/form-data">
    
    0 讨论(0)
  • 2020-12-07 15:57

    Spring documentation to disable csrf: https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#csrf-configure

    @EnableWebSecurity
    public class WebSecurityConfig extends
    WebSecurityConfigurerAdapter {
    
       @Override
       protected void configure(HttpSecurity http) throws Exception {
          http.csrf().disable();
       }
    }
    
    0 讨论(0)
  • 2020-12-07 15:57

    i think csrf only works with spring forms

    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    

    change to form:form tag and see it that works.

    0 讨论(0)
  • 2020-12-07 15:58

    Try to change this: <csrf /> to this : <csrf disabled="true"/>. It should disable csfr.

    0 讨论(0)
  • 2020-12-07 15:59

    If you will apply security="none" then no csrf token will be generated. The page will not pass through security filter. Use role ANONYMOUS.

    I have not gone in details, but it is working for me.

     <http auto-config="true" use-expressions="true">
       <intercept-url pattern="/login.jsp" access="hasRole('ANONYMOUS')" />
       <!-- you configuration -->
       </http>
    
    0 讨论(0)
提交回复
热议问题