title: Spring security CORS Filter
body: <p>We added <code>Spring Security</code> to our existing project.</p>
  <p>From this moment on we get a 401 <code>No 'Access-Control-Allow-Origin' header is present on the requested resource</code> error from the our server.</p>
  <p>That's because no <code>Access-Control-Allow-Origin</code> header is attached to the response. To fix this we added our own filter which is in the <code>Filter</code> chain before the logout filter, but the filter does not apply for our requests.</p>
  <p>Our Error:</p>
  <blockquote>
  <p>XMLHttpRequest cannot load <code>http://localhost:8080/getKunden</code>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin <code>http://localhost:3000</code> is therefore not allowed access. The response had HTTP status code 401.</p>
  </blockquote>
  <p>Our Security configuration:</p>
  <pre><code>@EnableWebSecurity
  @Configuration
  @ComponentScan(&quot;com.company.praktikant&quot;)
  public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
  
  @Autowired
  private MyFilter filter;
  
  @Override
  public void configure(HttpSecurity http) throws Exception {
      final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
      final CorsConfiguration config = new CorsConfiguration();
  
      config.addAllowedOrigin(&quot;*&quot;);
      config.addAllowedHeader(&quot;*&quot;);
      config.addAllowedMethod(&quot;GET&quot;);
      config.addAllowedMethod(&quot;PUT&quot;);
      config.addAllowedMethod(&quot;POST&quot;);
      source.registerCorsConfiguration(&quot;/**&quot;, config);
      http.addFilterBefore(new MyFilter(), LogoutFilter.class).authorizeRequests()
              .antMatchers(HttpMethod.OPTIONS, &quot;/*&quot;).permitAll();
  }
  
  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
  }
  }
  </code></pre>
  <p>Our filter</p>
  <pre><code>@Component
  public class MyFilter extends OncePerRequestFilter {
  
  @Override
  public void destroy() {
  
  }
  
  private String getAllowedDomainsRegex() {
      return &quot;individual / customized Regex&quot;;
  }
  
  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
          throws ServletException, IOException {
  
      final String origin = &quot;http://localhost:3000&quot;;
  
      response.addHeader(&quot;Access-Control-Allow-Origin&quot;, origin);
      response.setHeader(&quot;Access-Control-Allow-Methods&quot;, &quot;POST, GET, OPTIONS&quot;);
      response.setHeader(&quot;Access-Control-Allow-Credentials&quot;, &quot;true&quot;);
      response.setHeader(&quot;Access-Control-Allow-Headers&quot;,
              &quot;content-type, x-gwt-module-base, x-gwt-permutation, clientid, longpush&quot;);
  
      filterChain.doFilter(request, response);
  
  }
  }
  </code></pre>
  <p>Our Application</p>
  <pre><code>@SpringBootApplication
  public class Application {
  public static void main(String[] args) {
      final ApplicationContext ctx = SpringApplication.run(Application.class, args);
      final AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext();
      annotationConfigApplicationContext.register(CORSConfig.class);
      annotationConfigApplicationContext.refresh();
  }
  }
  </code></pre>
  <p>Our filter is registered from spring-boot:</p>
  <blockquote>
  <p>2016-11-04 09:19:51.494  INFO 9704 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'myFilter' to: [/*]</p>
  </blockquote>
  <p>Our generated filterchain:</p>
  <blockquote>
  <p>2016-11-04 09:19:52.729  INFO 9704 --- [ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@5d8c5a8a, org.springframework.security.web.context.SecurityContextPersistenceFilter@7d6938f, org.springframework.security.web.header.HeaderWriterFilter@72aa89c, org.springframework.security.web.csrf.CsrfFilter@4af4df11, com.company.praktikant.MyFilter@5ba65db2, org.springframework.security.web.authentication.logout.LogoutFilter@2330834f, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@396532d1, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@4fc0f1a2, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@2357120f, org.springframework.security.web.session.SessionManagementFilter@10867bfb, org.springframework.security.web.access.ExceptionTranslationFilter@4b8bf1fb, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@42063cf1]</p>
  </blockquote>
  <p>The Response:
  <a href="https://i.stack.imgur.com/tw8pd.png" rel="noreferrer">Response headers</a></p>
  <p>We tried the solution from spring as well but it didn't work! The annotation @CrossOrigin in our controller didn't help either.</p>
  <h1>Edit 1:</h1>
  <p>Tried the solution from @Piotr Sołtysiak.
  The cors filter isn't listed in the generated filter chain and we still get the same error.</p>
  <blockquote>
  <p>2016-11-04 10:22:49.881  INFO 8820 --- [ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@4c191377, org.springframework.security.web.context.SecurityContextPersistenceFilter@28bad32a, org.springframework.security.web.header.HeaderWriterFilter@3c3ec668, org.springframework.security.web.csrf.CsrfFilter@288460dd, org.springframework.security.web.authentication.logout.LogoutFilter@1c9cd096, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@3990c331, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@1e8d4ac1, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@2d61d2a4, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@380d9a9b, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@abf2de3, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@2a5c161b, org.springframework.security.web.session.SessionManagementFilter@3c1fd3e5, org.springframework.security.web.access.ExceptionTranslationFilter@3d7055ef, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@5d27725a]</p>
  </blockquote>
  <p>Btw we are using spring-security version 4.1.3.!</p>