title: How to configure CORS in a Spring Boot + Spring Security application?
body: <p>I use Spring Boot with Spring Security and Cors Support. </p>
  
  <p>If I execute following code </p>
  
  <pre><code>url = 'http://localhost:5000/api/token'
  xmlhttp = new XMLHttpRequest
  xmlhttp.onreadystatechange = -&gt;
      if xmlhttp.readyState is 4
          console.log xmlhttp.status
  xmlhttp.open "GET", url, true
  # xmlhttp.setRequestHeader "X-Requested-With", "XMLHttpRequest"
  xmlhttp.setRequestHeader 'Authorization', 'Basic ' + btoa 'a:a'
  do xmlhttp.send
  </code></pre>
  
  <p>I get as a result</p>
  
  <pre><code>200
  </code></pre>
  
  <p>If I test with wrong credentials like</p>
  
  <pre><code>url = 'http://localhost:5000/api/token'
  xmlhttp = new XMLHttpRequest
  xmlhttp.onreadystatechange = -&gt;
      if xmlhttp.readyState is 4
          console.log xmlhttp.status
  xmlhttp.open "GET", url, true
  # xmlhttp.setRequestHeader "X-Requested-With", "XMLHttpRequest"
  xmlhttp.setRequestHeader 'Authorization', 'Basic ' + btoa 'a:aa'
  do xmlhttp.send
  </code></pre>
  
  <p>instead of getting 401 (that is the standard code for wrong authentication in spring security) I get</p>
  
  <pre><code>0
  </code></pre>
  
  <p>with following browser notification:</p>
  
  <p>GET <a href="http://localhost:5000/api/token" rel="noreferrer">http://localhost:5000/api/token</a></p>
  
  <p>XMLHttpRequest cannot load <a href="http://localhost:5000" rel="noreferrer">http://localhost:5000</a>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '<a href="http://localhost:3000" rel="noreferrer">http://localhost:3000</a>' is therefore not allowed access. The response had HTTP status code 401.</p>
  
  <p>I'm developing front-end code that needs useful http status codes from server responses to handle the situation. I need something more useful than 0. Also the response body is empty. I dont know if my config is wrong, or it's a software bug and I also don't know where, if it's chromium (using arch linux) or spring security.</p>
  
  <p>My Spring Config is:</p>
  
  <pre><code>@SpringBootApplication
  public class Application {
      public static void main(String[] args) {
          SpringApplication.run(Application.class, args);
      }
  }
  
  @RestController
  @RequestMapping("api")
  public class Controller {
      @RequestMapping("token")
      @CrossOrigin
      Map&lt;String, String&gt; token(HttpSession session) {
          return Collections.singletonMap("token", session.getId());
      }
  }
  
  @EnableWebSecurity
  public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.inMemoryAuthentication().withUser("a").password("a").roles("USER");
      }
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
                  .authorizeRequests()
                  .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                  .anyRequest().authenticated()
                  .and().httpBasic();
      }
  }
  </code></pre>
  
  <p>If I test with curl everything works perfect, I think because no CORS support needed, but I tried to simulate the CORS with OPTION requests and the result was also ok.</p>
  
  <pre><code>$ curl -v localhost:5000/api/token -H "Authorization: Basic YTpha"
  *   Trying ::1...
  * Connected to localhost (::1) port 5000 (#0)
  &gt; GET /api/token HTTP/1.1
  &gt; Host: localhost:5000
  &gt; User-Agent: curl/7.48.0
  &gt; Accept: */*
  &gt; Authorization: Basic YTpha
  &gt; 
  &lt; HTTP/1.1 200 OK
  &lt; Server: Apache-Coyote/1.1
  &lt; X-Content-Type-Options: nosniff
  &lt; X-XSS-Protection: 1; mode=block
  &lt; Cache-Control: no-cache, no-store, max-age=0, must-revalidate
  &lt; Pragma: no-cache
  &lt; Expires: 0
  &lt; X-Frame-Options: DENY
  &lt; Access-Control-Allow-Origin: http://localhost:3000
  &lt; Access-Control-Allow-Methods: POST,GET,OPTIONS,DELETE
  &lt; Access-Control-Max-Age: 3600
  &lt; Access-Control-Allow-Credentials: true
  &lt; Access-Control-Allow-Headers: Origin,Accept,X-Requested-    With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization
  &lt; x-auth-token: 58e4cca9-7719-46c8-9180-2fc16aec8dff
  &lt; Content-Type: application/json;charset=UTF-8
  &lt; Transfer-Encoding: chunked
  &lt; Date: Sun, 01 May 2016 16:15:44 GMT
  &lt; 
  * Connection #0 to host localhost left intact
  {"token":"58e4cca9-7719-46c8-9180-2fc16aec8dff"}
  </code></pre>
  
  <p>and with wrong credentials:</p>
  
  <pre><code>$ curl -v localhost:5000/api/token -H "Authorization: Basic YTp"
  *   Trying ::1...
  * Connected to localhost (::1) port 5000 (#0)
  &gt; GET /api/token HTTP/1.1
  &gt; Host: localhost:5000
  &gt; User-Agent: curl/7.48.0
  &gt; Accept: */*
  &gt; Authorization: Basic YTp
  &gt; 
  &lt; HTTP/1.1 401 Unauthorized
  &lt; Server: Apache-Coyote/1.1
  &lt; X-Content-Type-Options: nosniff
  &lt; X-XSS-Protection: 1; mode=block
  &lt; Cache-Control: no-cache, no-store, max-age=0, must-revalidate
  &lt; Pragma: no-cache
  &lt; Expires: 0
  &lt; X-Frame-Options: DENY
  &lt; WWW-Authenticate: Basic realm="Realm"
  &lt; Content-Type: application/json;charset=UTF-8
  &lt; Transfer-Encoding: chunked
  &lt; Date: Sun, 01 May 2016 16:16:15 GMT
  &lt; 
  * Connection #0 to host localhost left intact
  {"timestamp":1462119375041,"status":401,"error":"Unauthorized","message":"Failed to decode basic authentication token","path":"/api/token"}
  </code></pre>
  
  <p>Edit:
  To avoid misunderstandings. I use 1.3.3 Spring Boot.
  The Blog post writes:</p>
  
  <blockquote>
    <p>CORS support will be available in the upcoming Spring Boot 1.3 release, and is already available in the 1.3.0.BUILD-SNAPSHOT builds.</p>
    
    <p>Using controller method CORS configuration with @CrossOrigin annotations in your Spring Boot application does not require any specific configuration.</p>
    
    <p>Global CORS configuration can be defined by registering a WebMvcConfigurer bean with a customized addCorsMappings(CorsRegistry) method:</p>
  </blockquote>
  
  <p>I have added following code to enable global cors support. actually I have tried this before but it the result was the same. I tried it again recently and the result is the same.</p>
  
  <pre><code>@Configuration
  public class MyConfiguration {
  
      @Bean
      public WebMvcConfigurer corsConfigurer() {
          return new WebMvcConfigurerAdapter() {
              @Override
              public void addCorsMappings(CorsRegistry registry) {
                  registry.addMapping("/**");
              }
          };
      }
  }
  </code></pre>
  
  <p>The idea, that the problem comes from a redirect between the authorization process is an interesting though. how can i change the redirect to any resources to avoid this conflict?</p>
  
  <p>EDIT:</p>
  
  <p>I guess I am closer to a solution. I have tested with my nodejs server that supports cors without problems by adding 
  Access-Control-Allow-Origin: *
  to all requests.</p>
  
  <p>Like Stefan Isele has already mentioned it seems that spring security redirects or doesn't add the CORS header so that's why the request seems to be broken. So while spring security is checking the authentification it has to add the proper header.</p>
  
  <p>Does anyone know how to do so?</p>
  
  <p>EDIT:</p>
  
  <p>I found a workaround, that seems to be ugly. I have started a github issue for spring boot where I describe the workaround: <a href="https://github.com/spring-projects/spring-boot/issues/5834" rel="noreferrer">https://github.com/spring-projects/spring-boot/issues/5834</a></p>