title: HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter
body: <p>I have to issue a HTTP.Post (Android App) to my restful service, to register a new user!</p>
  
  <p>The problem is, when I try to issue a request to a register endpoint ( without security ), Spring keeps blocking me!</p>
  
  <p>My Project Dependencies</p>
  
  <pre><code>&lt;properties&gt;
      &lt;java-version&gt;1.6&lt;/java-version&gt;
      &lt;org.springframework-version&gt;4.1.7.RELEASE&lt;/org.springframework-version&gt;
      &lt;org.aspectj-version&gt;1.6.10&lt;/org.aspectj-version&gt;
      &lt;org.slf4j-version&gt;1.6.6&lt;/org.slf4j-version&gt;
      &lt;jackson.version&gt;1.9.10&lt;/jackson.version&gt;
      &lt;spring.security.version&gt;4.0.2.RELEASE&lt;/spring.security.version&gt;
      &lt;hibernate.version&gt;4.2.11.Final&lt;/hibernate.version&gt;
      &lt;jstl.version&gt;1.2&lt;/jstl.version&gt;
      &lt;mysql.connector.version&gt;5.1.30&lt;/mysql.connector.version&gt;
  &lt;/properties&gt;
  </code></pre>
  
  <p>Spring Security</p>
  
  <pre><code>&lt;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"&gt;
  
  &lt;!--this is the register endpoint--&gt;
  &lt;http security="none" pattern="/webapi/cadastro**"/&gt;
  
  
      &lt;http auto-config="true" use-expressions="true"&gt;
                  &lt;intercept-url pattern="/webapi/dados**"
              access="hasAnyRole('ROLE_USER','ROLE_SYS')" /&gt;
          &lt;intercept-url pattern="/webapi/system**"
              access="hasRole('ROLE_SYS')" /&gt;
  
  &lt;!--        &lt;access-denied-handler error-page="/negado" /&gt; --&gt;
          &lt;form-login login-page="/home/" default-target-url="/webapi/"
              authentication-failure-url="/home?error" username-parameter="username"
              password-parameter="password" /&gt;
          &lt;logout logout-success-url="/home?logout" /&gt;        
          &lt;csrf token-repository-ref="csrfTokenRepository" /&gt;
      &lt;/http&gt;
  
      &lt;authentication-manager&gt;
          &lt;authentication-provider&gt;
              &lt;password-encoder hash="md5" /&gt;
              &lt;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 = ?" /&gt;
          &lt;/authentication-provider&gt;
      &lt;/authentication-manager&gt;
  
      &lt;beans:bean id="csrfTokenRepository"
          class="org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository"&gt;
          &lt;beans:property name="headerName" value="X-XSRF-TOKEN" /&gt;
      &lt;/beans:bean&gt;
  
  &lt;/beans:beans&gt;
  </code></pre>
  
  <p>Controller</p>
  
  <pre><code>@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";
       }
  }
  </code></pre>
  
  <p>JS Post ( Angular )</p>
  
  <pre><code>$http.post('/webapi/cadastro/novo').success(function(data) {
              alert('ok');
           }).error(function(data) {
               alert(data);
           });
  </code></pre>
  
  <p>And the error</p>
  
  <pre><code>HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.&lt;/h1&gt;&lt;HR size="1" noshade="noshade"&gt;&lt;p&gt;&lt;b&gt;type&lt;/b&gt; Status report&lt;/p&gt;&lt;p&gt;&lt;b&gt;message&lt;/b&gt; &lt;u&gt;Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'
  </code></pre>
  
  <p><strong>--- Solution ---</strong></p>
  
  <p>Implemented a filter to attach my X-XSRF-TOKEN to every request header</p>
  
  <pre><code>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 &amp;&amp; !token.equals(cookie.getValue())) {
          cookie = new Cookie("XSRF-TOKEN", token);
          cookie.setPath("/");
          response.addCookie(cookie);
        }
      }
      filterChain.doFilter(request, response);
    }
  }
  </code></pre>
  
  <p>Added a mapping to this filter to the web.xml and done!</p>