I'm using Spring Boot to make a simple rest service. To consume it in Angular 2, I've got CORS problem when retrieving token on OAuth /token endpoint.
The error message in Chrome is below.
zone.js:101 OPTIONS http://192.168.0.9:8080/api/oauth/token
XMLHttpRequest cannot load http://192.168.0.9: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:3000' is therefore not allowed access. The response had HTTP status code 401.
The related files are below.
MyConfig.java
@Configuration
public class MyConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("**")
.allowedOrigins("*").allowedMethods("POST, GET, HEAD, OPTIONS")
.allowCredentials(true)
.allowedHeaders("Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers")
.exposedHeaders("Access-Control-Allow-Origin,Access-Control-Allow-Credentials")
.maxAge(10);
}
};
}
}
OAuth2ResourceServerConfig.java
@Configuration
@EnableResourceServer
class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.anonymous()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS,"**").permitAll()
.antMatchers("/authenticated/**").authenticated()
;
}
}
I'm new to Java and spring. I found some similar question, such as OAuth2 - Status 401 on OPTIONS request while retrieving TOKEN, but I really don't understand how to make it work in Spring Boot.
Please note normal rest controller endpoint works fine. The problem is OAuth /token, the options request returns 401 status.