복붙노트

[SPRING] 요청 매개 변수 '_csrf'또는 헤더 'X-CSRF-TOKEN'에서 유효하지 않은 CSRF 토큰 'null'

SPRING

요청 매개 변수 '_csrf'또는 헤더 'X-CSRF-TOKEN'에서 유효하지 않은 CSRF 토큰 'null'

Spring Security 3.2를 설정 한 후 _csrf.token은 요청이나 세션 객체에 바인딩되지 않습니다.

이것은 스프링 보안 설정입니다 :

<http pattern="/login.jsp" security="none"/>

<http>
    <intercept-url pattern="/**" access="ROLE_USER"/>
    <form-login login-page="/login.jsp"
                authentication-failure-url="/login.jsp?error=1"
                default-target-url="/index.jsp"/>
    <logout/>
    <csrf />
</http>

<authentication-manager>
    <authentication-provider>
        <user-service>
            <user name="test" password="test" authorities="ROLE_USER/>
        </user-service>
    </authentication-provider>
</authentication-manager>

login.jsp 파일

<form name="f" action="${contextPath}/j_spring_security_check" method="post" >
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
    <button id="ingresarButton"
            name="submit"
            type="submit"
            class="right"
            style="margin-right: 10px;">Ingresar</button>
    <span>
        <label for="usuario">Usuario :</label>
        <input type="text" name="j_username" id="u" class="" value=''/>
    </span>
    <span>
        <label for="clave">Contrase&ntilde;a :</label>

        <input type="password"
               name="j_password"
               id="p"
               class=""
               onfocus="vc_psfocus = 1;"
               value="">
    </span>
</form>

그리고 다음 HTML을 렌더링합니다.

<input type="hidden" name="" value="" />

결과는 403 HTTP 상태입니다.

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

최신 정보 일부 디버그 후, 요청 객체는 훌륭한 형식의 DelegatingFilterProxy를 얻지 만, CoyoteAdapter의 469 번째 줄에서는 request.recycle (); 모든 속성을 삭제합니다 ...

JDK 1.7을 사용하여 Tomcat 6.0.36, 7.0.50에서 테스트합니다.

나는이 행동을 이해하지 못했다. 누군가 CSRF와 함께 작동하는 Spring Security 3.2와의 몇 가지 애플리케이션 샘플 전쟁의 방향으로 나를 가리킨다면 가능할 것이다.

해결법

  1. ==============================

    1.Spring 애플리케이션의 CSRF (Cross Site Request Forgery) 보호가 활성화 된 것처럼 보입니다. 사실 기본적으로 활성화되어 있습니다.

    Spring 애플리케이션의 CSRF (Cross Site Request Forgery) 보호가 활성화 된 것처럼 보입니다. 사실 기본적으로 활성화되어 있습니다.

    spring.io에 따르면 :

    그래서 그것을 비활성화하려면 :

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

    그래도 CSRF 보호 기능을 계속 사용하려면 csrftoken을 양식에 포함시켜야합니다. 다음과 같이 할 수 있습니다.

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

    CSRF 토큰을 양식의 작업에 포함시킬 수도 있습니다.

    <form action="./upload?${_csrf.parameterName}=${_csrf.token}" method="post" enctype="multipart/form-data">
    
  2. ==============================

    2.로그인 폼에 추가해서는 안됩니까?

    로그인 폼에 추가해서는 안됩니까?

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

    Spring 보안 문서의 여기에 언급 된 것처럼

  3. ==============================

    3.security = "none"을 적용하면 csrf 토큰이 생성되지 않습니다. 페이지가 보안 필터를 통과하지 않습니다. ANONYMOUS 역할을 사용하십시오.

    security = "none"을 적용하면 csrf 토큰이 생성되지 않습니다. 페이지가 보안 필터를 통과하지 않습니다. ANONYMOUS 역할을 사용하십시오.

    나는 세부 사항에 가지 않았지만 그것은 나를 위해 일하고있다.

     <http auto-config="true" use-expressions="true">
       <intercept-url pattern="/login.jsp" access="hasRole('ANONYMOUS')" />
       <!-- you configuration -->
       </http>
    
  4. ==============================

    4.로 변경하십시오. csrf를 비활성화해야합니다.

    로 변경하십시오. csrf를 비활성화해야합니다.

  5. ==============================

    5.thymeleaf를 사용하면 다음을 추가 할 수 있습니다.

    thymeleaf를 사용하면 다음을 추가 할 수 있습니다.

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

    6.csrf를 비활성화하는 스프링 문서 : https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#csrf-configure

    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();
       }
    }
    
  7. ==============================

    7.나는 같은 문제가 있었었다.

    나는 같은 문제가 있었었다.

    귀하의 설정은 security = "none"을 사용하므로 _csrf를 생성 할 수 없습니다 :

    <http pattern="/login.jsp" security="none"/>
    

    당신은 위의 /login.jsp 페이지에 대해 access = "IS_AUTHENTICATED_ANONYMOUSLY"를 설정할 수 있습니다 :

    <http>
        <intercept-url pattern="/login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
        <intercept-url pattern="/**" access="ROLE_USER"/>
        <form-login login-page="/login.jsp"
                authentication-failure-url="/login.jsp?error=1"
                default-target-url="/index.jsp"/>
        <logout/>
        <csrf />
    </http>
    
  8. ==============================

    8.나는 csrf가 스프링 양식에서만 작동한다고 생각합니다.

    나는 csrf가 스프링 양식에서만 작동한다고 생각합니다.

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

    form : form 태그로 바꾸고 작동하는 것을 본다.

  9. ==============================

    9.Github의 샘플 샘플 응용 프로그램을보고 설정과 비교하십시오.

    Github의 샘플 샘플 응용 프로그램을보고 설정과 비교하십시오.

  10. ==============================

    10.솔루션 중 어느 것도 작동하지 않습니다. Spring 폼에서 저에게 도움이 된 유일한 것은 :

    솔루션 중 어느 것도 작동하지 않습니다. Spring 폼에서 저에게 도움이 된 유일한 것은 :

    action = "./ upload? $ {_ csrf.parameterName} = $ {_ csrf.token}"

    교체 대상 :

    action = "./ upload? _csrf = $ {_ csrf.token}"

    (Java 구성에서 csrf가 활성화 된 스프링 5)

  11. ==============================

    11.컨트롤러에 다음을 추가하십시오.

    컨트롤러에 다음을 추가하십시오.

    @RequestParam(value = "_csrf", required = false) String csrf
    

    그리고 jsp 페이지에서 add

    <form:form modelAttribute="someName" action="someURI?${_csrf.parameterName}=${_csrf.token}
    
  12. ==============================

    12.봄 보안을 위해 4.2.3 버전의 jar 파일을 사용했지만 동일한 오류가 발생했습니다. 그럼 내가 3.1.4로 다운 그레이드하고 완벽하게 작동합니다.

    봄 보안을 위해 4.2.3 버전의 jar 파일을 사용했지만 동일한 오류가 발생했습니다. 그럼 내가 3.1.4로 다운 그레이드하고 완벽하게 작동합니다.

    다음은 pom.xml의 내 종속성입니다.

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>3.2.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.26</version>
    </dependency>
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate</artifactId>
        <version>3.5.4-Final</version>
        <type>pom</type>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.0.1.Final</version>
    </dependency>
    <dependency>
        <groupId>commons-validator</groupId>
        <artifactId>commons-validator</artifactId>
        <version>1.4.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>3.1.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>3.1.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>3.1.4.RELEASE</version>
    </dependency>
    
  13. from https://stackoverflow.com/questions/21128058/invalid-csrf-token-null-was-found-on-the-request-parameter-csrf-or-header by cc-by-sa and MIT license