title: Spring CSRF + AngularJs
body: <p>I Already tried many of the aswers about this topic, no one works for me.</p>
  
  <p>I Have a basic CRUD with Spring MVC 4.1.7, Spring Security 3.2.3 working on MySQL + Tomcat7.</p>
  
  <p>The problem is, when i try to POST form with AngularJS, I keep being blocked by error 403 ( access denied ).</p>
  
  <p>I figured out that I need to send my CSRF_TOKEN with the POST request, but I can't figure out HOW!</p>
  
  <p>I Tried so many diferent ways and no one works.</p>
  
  <p>My Files</p>
  
  <p>Controller.js</p>
  
  <pre><code>$scope.novo = function novo() {
    if($scope.id){
     alert("Update - " + $scope.id);
    }
    else{
        var Obj = {
                descricao : 'Test',
                saldo_inicial : 0.00,
                saldo : 33.45,
                aberto : false,
                usuario_id : null,
                ativo : true
        };
        $http.post(urlBase + 'caixas/adicionar', Obj).success(function(data) {
            $scope.caixas = data;    
        }).error(function(data) {alert(data)});
    }
   };
  </code></pre>
  
  <p>Spring-security.xml</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;!-- enable use-expressions --&gt;
  &lt;http auto-config="true" use-expressions="true"&gt;
      &lt;intercept-url pattern="/seguro**"
          access="hasAnyRole('ROLE_USER','ROLE_ADMIN')" /&gt;
      &lt;intercept-url pattern="/seguro/financeiro**"
          access="hasAnyRole('ROLE_FINANCEIRO','ROLE_ADMIN')" /&gt;
  
      &lt;!-- access denied page --&gt;
      &lt;access-denied-handler error-page="/negado" /&gt;
      &lt;form-login login-page="/home/" default-target-url="/seguro/"
          authentication-failure-url="/home?error" username-parameter="inputEmail"
          password-parameter="inputPassword" /&gt;
      &lt;logout logout-success-url="/home?logout" /&gt;
      &lt;!-- enable csrf protection --&gt;
      &lt;csrf /&gt;
  &lt;/http&gt;
  
  &lt;!-- Select users and user_roles from database --&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 login, senha, ativo
                 FROM usuarios 
                WHERE login = ?"
              authorities-by-username-query="SELECT u.login, r.role
                 FROM usuarios_roles r, usuarios u
                WHERE u.id = r.usuario_id
                  AND u.login = ?" /&gt;
      &lt;/authentication-provider&gt;
  &lt;/authentication-manager&gt;
  </code></pre>
  
  <p></p>
  
  <p>web.xml</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"&gt;
  
  &lt;display-name&gt;Barattie ~ Soluções Integradas&lt;/display-name&gt;
  
  &lt;!-- The definition of the Root Spring Container shared by all Servlets 
      and Filters --&gt;
  &lt;context-param&gt;
      &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
      &lt;param-value&gt;
          /WEB-INF/spring/spring-security.xml
          /WEB-INF/spring/spring-database.xml
          /WEB-INF/spring/spring-hibernate.xml
      &lt;/param-value&gt;
  &lt;/context-param&gt;
  &lt;context-param&gt;
      &lt;param-name&gt;com.sun.faces.writeStateAtFormEnd&lt;/param-name&gt;
      &lt;param-value&gt;false&lt;/param-value&gt;
  &lt;/context-param&gt;
  
  &lt;!-- Creates the Spring Container shared by all Servlets and Filters --&gt;
  &lt;listener&gt;
      &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
  &lt;/listener&gt;
  
  &lt;!-- Processes application requests --&gt;
  &lt;servlet&gt;
      &lt;servlet-name&gt;appServlet&lt;/servlet-name&gt;
      &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
      &lt;init-param&gt;
          &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
          &lt;param-value&gt;/WEB-INF/spring/appServlet/servlet-context.xml&lt;/param-value&gt;
      &lt;/init-param&gt;
      &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
  &lt;/servlet&gt;
  
  &lt;servlet-mapping&gt;
      &lt;servlet-name&gt;appServlet&lt;/servlet-name&gt;
      &lt;url-pattern&gt;/home&lt;/url-pattern&gt;
      &lt;url-pattern&gt;/&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
  
  &lt;!-- Spring Security --&gt;
  &lt;filter&gt;
      &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
      &lt;filter-class&gt;org.springframework.web.filter.DelegatingFilterProxy&lt;/filter-class&gt;
  &lt;/filter&gt;
  
  &lt;filter-mapping&gt;
      &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
      &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
  &lt;/filter-mapping&gt;
  
  &lt;error-page&gt;
      &lt;exception-type&gt;java.lang.Throwable&lt;/exception-type&gt;
      &lt;location&gt;/erro&lt;/location&gt;
  &lt;/error-page&gt;
  </code></pre>
  
  <p></p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I tried to add to rename at client side the xsrf, but I keep getting access denied.</p>
  
  <pre><code>var app = angular.module('myApp', []).config(function($httpProvider) {
  $httpProvider.defaults.xsrfCookieName = '_csrf';
  $httpProvider.defaults.xsrfHeaderName = 'X-CSRF-Token';
  });
  </code></pre>
  
  <p>** UPDATE 2 **</p>
  
  <p>I tried to implement a filter like this.</p>
  
  <pre><code>package sys.barattie.util;
  
  import java.io.IOException;
  
  import javax.servlet.FilterChain;
  import javax.servlet.ServletException;
  import javax.servlet.http.Cookie;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  
  import org.springframework.security.web.csrf.CsrfToken;
  import org.springframework.web.filter.OncePerRequestFilter;
  
  public class CsrfFilter 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 = new Cookie("XSRF-TOKEN", csrf.getToken());
          cookie.setPath("/");
          response.addCookie(cookie);
      }
      filterChain.doFilter(request, response);
  }
  }
  </code></pre>
  
  <p>And changed my spring security to it.</p>
  
  <pre><code>     &lt;csrf token-repository-ref="csrfTokenRepository" /&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;
  </code></pre>
  
  <p>Web.xml</p>
  
  <pre><code>&lt;filter&gt;
      &lt;filter-name&gt;csrfFilter&lt;/filter-name&gt;
      &lt;filter-class&gt;sys.barattie.util.CsrfFilter&lt;/filter-class&gt;
  &lt;/filter&gt;
  </code></pre>
  
  <p>But it is like that the server doesn't run the filter, I've added a System.out.println to it, but can't see the messages in the debug</p>