title: CORS doesn't work on Spring 4.3 with OAuth2
body: <p>Here is what I'm getting in Chrome console when issuing request using Angular 1.5 app:</p>
  
  <blockquote>
    <p>XMLHttpRequest cannot load <a href="http://localhost:8080/api/oauth/token" rel="nofollow noreferrer">http://localhost:8080/api/oauth/token</a>.
    Response to preflight request doesn't pass access control check: No
    'Access-Control-Allow-Origin' header is present on the requested
    resource. Origin '<a href="http://localhost:8000" rel="nofollow noreferrer">http://localhost:8000</a>' is therefore not allowed
    access. The response had HTTP status code 401.</p>
  </blockquote>
  
  <p>When I remove OAuth2 configuration, error is gone.</p>
  
  <p>This my CORS config:</p>
  
  <pre><code>class AppWebSpringConfig extends WebMvcConfigurerAdapter implements ServletContextAware {
  
  ...
  
      @Override
      public void addCorsMappings(CorsRegistry registry) {
          registry.addMapping("/**")
                  .allowedOrigins("*")
                  .allowedMethods("GET", "POST", "PUT", "DELETE")
                  .allowedHeaders("X-Requested-With", "X-Auth-Token", "Origin", "Content-Type", "Accept")
                  .allowCredentials(false)
                  .maxAge(3600);
      }
  
  ...
  }
  </code></pre>
  
  <p>And my OAuth2 config classes:</p>
  
  <pre><code>@Configuration
  @EnableGlobalMethodSecurity(prePostEnabled = true)
  class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
  
      @Override
      protected MethodSecurityExpressionHandler createExpressionHandler() {
          return new OAuth2MethodSecurityExpressionHandler();
      }
  
  }
  
  @Configuration
  class OAuth2ServerConfiguration {
  
      private static final int ONE_HOUR = 3600;
      private static final int THIRTY_DAYS = 2592000;
  
      @Configuration
      @EnableResourceServer
      protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
  
          @Override
          public void configure(HttpSecurity http) throws Exception {
              // @formatter:off
              http
                      .authorizeRequests()
                      .anyRequest().authenticated();
              // @formatter:on
          }
  
      }
  
      @Configuration
      @EnableAuthorizationServer
      protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
  
          @Autowired
          @Qualifier("authenticationManagerBean")
          private AuthenticationManager authenticationManager;
  
          @Autowired
          private UserSecurityService userSecurityService;
  
          @Autowired
          private DataSource dataSource;
  
          @Autowired
          private Environment env;
  
          @Override
          public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
              // @formatter:off
              endpoints
                      .tokenStore(tokenStore())
                      .authenticationManager(authenticationManager)
                      .userDetailsService(userSecurityService);
              // @formatter:on
          }
  
          @Bean
          public TokenStore tokenStore() {
              return new JdbcTokenStore(dataSource);
          }
  
          @Override
          public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
              // @formatter:off
              clients
                      .jdbc(dataSource)
                      .withClient(env.getProperty(CLIENT_ID_WEB))
                      .secret(env.getProperty(CLIENT_SECRET_WEB))
                      .authorizedGrantTypes("password", "refresh_token")
                      .scopes("read", "write")
                      .accessTokenValiditySeconds(ONE_HOUR)
                      .refreshTokenValiditySeconds(THIRTY_DAYS);
              // @formatter:on
          }
  
          @Bean
          @Primary
          public DefaultTokenServices tokenServices() {
              final DefaultTokenServices tokenServices = new DefaultTokenServices();
              tokenServices.setSupportRefreshToken(true);
              tokenServices.setTokenStore(tokenStore());
              return tokenServices;
          }
  
      }
  
  }
  </code></pre>
  
  <p>EDIT: I also tried with following filter implementation, but it doesn't work. I put a breakpoint in doFilter() method, but execution doesn't stop there, like my filter is not registered. However, when I added a default constructor to filter and put a breakpoint there - it stopped, which means that filter is registered.</p>
  
  <pre><code>@Component
  @Order(Ordered.HIGHEST_PRECEDENCE)
  public class SimpleCorsFilter implements Filter {
  
      public SimpleCorsFilter() {
      }
  
      @Override
      public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
          HttpServletResponse response = (HttpServletResponse) res;
          HttpServletRequest request = (HttpServletRequest) req;
          response.setHeader("Access-Control-Allow-Origin", "*");
          response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
          response.setHeader("Access-Control-Max-Age", "3600");
          response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");
  
          if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
              response.setStatus(HttpServletResponse.SC_OK);
          } else {
              chain.doFilter(req, res);
          }
      }
  
      @Override
      public void init(FilterConfig filterConfig) {
      }
  
      @Override
      public void destroy() {
      }
  }
  </code></pre>
  
  <p>I also tried with this approach, but no luck once again: <a href="https://stackoverflow.com/questions/25136532/allow-options-http-method-for-oauth-token-request">Allow OPTIONS HTTP Method for oauth/token request</a></p>
  
  <p>I think that OAuth2 configuration is not allowing to request to even get through configured CORS filter.
  Does someone know a solution to this problem?</p>
  
  <p>EDIT2:
  So, it turns out that there was a class:</p>
  
  <pre><code>public class AppSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
  
      // nothing here, using defaults
  
  }
  </code></pre>
  
  <p>Once i commented it, CORS configuration started working (probably due to filters passing) BUT now my OAuth2 configuration is not working at all! Every URL is exposed, without security. Any thoughts?</p>