[android]HTTP 状态 403-无效 CSRF 令牌 null 被发现对请求参数

发布时间: 2017/3/17 1:44:35
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我不得不发出 HTTP。开机自检 ( Android 应用程序) 对我宁静 service ,注册一个新用户 !

问题是,当我尝试请求发给注册端点 (不安全),弹簧保持阻止我 !

我的项目依赖项

<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 发布 (角)

$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'

---解决方案--

执行 filter 将我 X XSRF 标记附加到每个请求标头

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);
  }
}

添加一个映射到这 filter 到 web.xml 做 !

解决方法 1:

在上述代码中,我看不见东西,会将 CSRF 令牌传递到客户端 (这是自动的如果你使用 JSP 等)。

流行的做法,这是对代码 filter 附加 CSRF 令牌作为一个 cookie。您的客户端然后将发送一个 GET 请求,第一次去取该 cookie。对于后续的请求,该 cookie 然后被发送回作为标题。

而官方春季角指南详细解释的那样,你可以引用Spring柠檬为一个完整的工作示例。

对于回到作为标题发送 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');

    }]);
赞助商