【发布时间】:2016-09-27 18:10:58
【问题描述】:
我正在使用 spring boot 来做一个简单的休息服务。为了在 Angular 2 中使用它,我在 oauth/token 端点上检索令牌时遇到了 CORS 问题。
Chrome 中的错误信息如下。
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.
相关文件如下。
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()
;
}
}
我是 java 和 spring 的新手。我发现了一些类似的问题,例如OAuth2 - Status 401 on OPTIONS request while retrieving TOKEN,但我真的不明白如何使它在spring boot中工作。
请注意正常的休息控制器端点工作正常。问题是oauth/token,options请求返回401状态。
请在 Spring Boot 中显示一些工作代码。谢谢!
【问题讨论】:
标签: rest spring-boot oauth-2.0 cors options