簡體   English   中英

HTTP狀態403 - 在請求參數上找到無效的CSRF令牌“null”

[英]HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter

我必須向我的restful服務發出HTTP.Post(Android App),以注冊新用戶!

問題是,當我嘗試向注冊終端發出請求(沒有安全性)時,Spring一直阻止我!

我的項目依賴關系

<properties>
    <java-version>1.6</java-version>
    <org.springframework-version>4.1.7.RELEASE</org.springframework-version>
    <org.aspectj-version>1.6.10</org.aspectj-version>
    <org.slf4j-version>1.6.6</org.slf4j-version>
    <jackson.version>1.9.10</jackson.version>
    <spring.security.version>4.0.2.RELEASE</spring.security.version>
    <hibernate.version>4.2.11.Final</hibernate.version>
    <jstl.version>1.2</jstl.version>
    <mysql.connector.version>5.1.30</mysql.connector.version>
</properties>

春季安全

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security.xsd">

<!--this is the register endpoint-->
<http security="none" pattern="/webapi/cadastro**"/>


    <http auto-config="true" use-expressions="true">
                <intercept-url pattern="/webapi/dados**"
            access="hasAnyRole('ROLE_USER','ROLE_SYS')" />
        <intercept-url pattern="/webapi/system**"
            access="hasRole('ROLE_SYS')" />

<!--        <access-denied-handler error-page="/negado" /> -->
        <form-login login-page="/home/" default-target-url="/webapi/"
            authentication-failure-url="/home?error" username-parameter="username"
            password-parameter="password" />
        <logout logout-success-url="/home?logout" />        
        <csrf token-repository-ref="csrfTokenRepository" />
    </http>

    <authentication-manager>
        <authentication-provider>
            <password-encoder hash="md5" />
            <jdbc-user-service data-source-ref="dataSource"
                users-by-username-query="SELECT username, password, ativo
                   FROM usuarios 
                  WHERE username = ?"
                authorities-by-username-query="SELECT u.username, r.role
                   FROM usuarios_roles r, usuarios u
                  WHERE u.id = r.usuario_id
                    AND u.username = ?" />
        </authentication-provider>
    </authentication-manager>

    <beans:bean id="csrfTokenRepository"
        class="org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository">
        <beans:property name="headerName" value="X-XSRF-TOKEN" />
    </beans:bean>

</beans:beans>

調節器

@RestController
@RequestMapping(value="/webapi/cadastro", produces="application/json")
public class CadastroController {
    @Autowired 
    UsuarioService usuarioService;

    Usuario u = new Usuario();

    @RequestMapping(value="/novo",method=RequestMethod.POST)
    public String register() {
        // this.usuarioService.insert(usuario);
        // usuario.setPassword(HashMD5.criptar(usuario.getPassword()));
        return "teste";
     }
}

JS Post(Angular)

$http.post('/webapi/cadastro/novo').success(function(data) {
            alert('ok');
         }).error(function(data) {
             alert(data);
         });

而錯誤

HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u>Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'

---解決方案---

實現了一個過濾器,將我的X-XSRF-TOKEN連接到每個請求標頭

public class CsrfHeaderFilter extends OncePerRequestFilter {
  @Override
  protected void doFilterInternal(HttpServletRequest request,
      HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {
    CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
        .getName());
    if (csrf != null) {
      Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
      String token = csrf.getToken();
      if (cookie==null || token!=null && !token.equals(cookie.getValue())) {
        cookie = new Cookie("XSRF-TOKEN", token);
        cookie.setPath("/");
        response.addCookie(cookie);
      }
    }
    filterChain.doFilter(request, response);
  }
}

添加到此過濾器的映射到web.xml並完成!

在上面的代碼中,我看不到會將CSRF令牌傳遞給客戶端的東西(如果你使用JSP等,這是自動的)。

一種流行的做法是編寫過濾器以將CSRF令牌作為cookie附加。 然后,您的客戶端首先發送GET請求以獲取該cookie。 對於后續請求,該cookie隨后將作為標頭發回。

官方的Spring Angular指南詳細解釋了這一點,您可以參考Spring Lemon獲取完整的工作示例。

要將cookie作為標題發回,您可能需要編寫一些代碼。 默認情況下,AngularJS會這樣做(除非您發送跨域請求),但這里有一個示例,如果它有助於您的客戶端不這樣做:

angular.module('appBoot')
  .factory('XSRFInterceptor', function ($cookies, $log) {

    var XSRFInterceptor = {

      request: function(config) {

        var token = $cookies.get('XSRF-TOKEN');

        if (token) {
          config.headers['X-XSRF-TOKEN'] = token;
          $log.info("X-XSRF-TOKEN: " + token);
        }

        return config;
      }
    };
    return XSRFInterceptor;
  });

angular.module('appBoot', ['ngCookies', 'ngMessages', 'ui.bootstrap', 'vcRecaptcha'])
    .config(['$httpProvider', function ($httpProvider) {

      $httpProvider.defaults.withCredentials = true;
      $httpProvider.interceptors.push('XSRFInterceptor');

    }]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM