I use spring boot to make a simple holiday service. To use it in Angular 2, I have a problem with CORS when extracting a token to the oauth / token endpoint.
Chrome error message below.
error message
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.
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 am new to java and spring. I found the same question as OAuth2 - Status 401 in an OPTIONS request when searching for TOKEN , but I really don't understand how to make it work in spring boot.
Note that the endpoint of the breakpoint controller is working fine. The problem is that oauth / token, requesting parameters returns 401 status.
Please show me some working code in spring boot. Thanks!
source share