Here is what I'm getting in Chrome console when issuing request using Angular 1.5 app:
XMLHttpRequest cannot load http://localhost:8080/api/oauth/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 401.
When I remove OAuth2 configuration, error is gone.
This my CORS config:
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);
}
...
}
And my OAuth2 config classes:
@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;
}
}
}
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.
@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() {
}
}
I also tried with this approach, but no luck once again: Allow OPTIONS HTTP Method for oauth/token request
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?
EDIT2: So, it turns out that there was a class:
public class AppSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
// nothing here, using defaults
}
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?