我正在使用spring引导进行简单的休息服务。为了在Angular 2中使用它,在oauth/token端点上检索标记时,我遇到了CORS问题。oauth /令牌上的弹簧引导休息服务选项401
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和春天。我发现了一些类似的问题,例如OAuth2 - Status 401 on OPTIONS request while retrieving TOKEN,但我真的不明白如何使它在春季启动中工作。
请注意正常的休息控制器端点工作正常。问题是oauth/token,选项请求返回401状态。
请在弹簧启动时给我看一些工作代码。谢谢!
我在其他帖子中找到了这个答案。但在Spring Boot中,它推荐使用WebMvcConfigurerAdapter,如我的代码所示,而不是过滤器。你可以看到他们有类似的代码,除了“OPTIONS”部分。所以我想知道是否可以添加类似的“选项”代码到我的文件?谢谢。 – weijun
你的代码有效! :) – weijun
非常感谢你!!!!!我花了大约4天的时间解决了这个问题后,你节省了我的一天! –