title: Spring-boot + Oauth2: CSRF ~ Restful API
body: <p>i'm learning Spring-boot and Oauth2. I  have a few problems.</p>
  
  <p>i'm implementing protection against CSRF</p>
  
  <pre><code>.csrf()
                  .requireCsrfProtectionMatcher(new AndRequestMatcher(
                      new NegatedRequestMatcher(new AntPathRequestMatcher("/test", HttpMethod.OPTIONS.toString()))
                  ));
  </code></pre>
  
  <p>this is working fine but when i try to access another path on my API i'm getting this message.</p>
  
  <pre><code>"error": "access_denied"
  "error_description": "Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'."
  </code></pre>
  
  <p>i tried to set the cookie with the JSESSIONID on my request but didn't work</p>
  
  <pre><code>Status
  403 Prohibido Show explanation Loading time: 22
  Request headers 
  Accept: application/json
  Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
  User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36
  Authorization: Bearer 4abe8cbc-a528-4d52-8e20-a0aa198056d2
  Content-Type: application/json 
  DNT: 1
  Accept-Encoding: gzip, deflate
  Accept-Language: es-ES,es;q=0.8,en;q=0.6,und;q=0.4
  Cookie: JSESSIONID=3DB726CA18F6628719703891B7DCA0A2
  Response headers 
  Server: Apache-Coyote/1.1 
  X-Content-Type-Options: nosniff
  X-XSS-Protection: 1; mode=block
  Cache-Control: no-cache, no-store, max-age=0, must-revalidate
  Pragma: no-cache
  Expires: 0 
  X-Frame-Options: DENY
  Cache-Control: no-store 
  Pragma: no-cache 
  Content-Type: application/json;charset=UTF-8 
  Transfer-Encoding: chunked 
  Date: Tue, 05 Jan 2016 03:59:45 GMT
  </code></pre>
  
  <p>Also i tried to set my CSRF filter on my project, was worst, this didn't get me the Cookie with the JSESSIONID. Literally do nothing</p>
  
  <pre><code>@Configuration
  @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
  @EnableWebSecurity
  public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
  
  @Autowired
  CustomAuthenticationProvider customAuthenticationProvider;
  
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
      auth.authenticationProvider(customAuthenticationProvider);
  }
  
  @Override
  @Bean
  public AuthenticationManager authenticationManagerBean() throws Exception {
      return super.authenticationManagerBean();
  }
  
  @Override
  protected void configure(HttpSecurity http) throws Exception {
      http.httpBasic().and().authorizeRequests()
              .antMatchers("/test").permitAll().anyRequest()
              .authenticated()
              .and().csrf()
              .csrfTokenRepository(csrfTokenRepository()).and()
              .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
  }
  
  private Filter csrfHeaderFilter() {
      return new 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);
          }
      };
  }
  
  private CsrfTokenRepository csrfTokenRepository() {
      HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
      repository.setHeaderName("X-XSRF-TOKEN");
      return repository;
  }
  }
  </code></pre>
  
  <p>Any idea what i'm doing wrong?</p>
  
  <p><strong>EDIT</strong> i've found a partial solution i think, but now i have a few questions.</p>
  
  <p><strong>Solution:</strong> 
  made my CrsfTokenRepository a <code>@Bean</code></p>
  
  <pre><code>@Bean
  public CsrfTokenRepository csrfTokenRepository() {
      HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
      repository.setHeaderName("X-XSRF-TOKEN");
      return repository;
  }
  </code></pre>
  
  <p>made a whole class only for my <code>CsrfHeaderFilter</code></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>and moved my configuration in <code>WebSecurityConfiguration</code> to my <code>Oauth2Configuration</code></p>
  
  <pre><code>@Configuration
  @EnableResourceServer
  protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
  
      @Autowired
      private CustomLogoutSuccessHandler customLogoutSuccessHandler;
  
      @Autowired
      private CsrfTokenRepository csrfTokenRepository;
  
      @Override
      public void configure(ResourceServerSecurityConfigurer resources) {
          resources
                  .resourceId(RESOURCE_ID);
      }
  
      @Override
      public void configure(HttpSecurity http) throws Exception {
          http
                  // Logout
                  .logout()
                  .logoutUrl("/oauth/logout")
                  .logoutSuccessHandler(customLogoutSuccessHandler)
                  .and()
                  //Session management
                  .sessionManagement()
                  .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                  .and()
                  //URI's to verify
                  .authorizeRequests()
                  .antMatchers("/test").hasRole("ADMIN")
                  .antMatchers("/users").authenticated()
                  .antMatchers("/**").authenticated()
                  .antMatchers("/productos").hasAnyRole("ADMIN, VENDEDOR")
                  .and()
                  .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
                  .csrf()
                  .csrfTokenRepository(csrfTokenRepository);
      }
  }
  </code></pre>
  
  <p><strong>My questions are:</strong></p>
  
  <ul>
  <li>This solution is fine? is a good practice?</li>
  <li>the JSESSIONID and the XSRF-Token dont need to be attached in my angularjs request?</li>
  </ul>