我有一个带有oauth2身份验证的spring-rest应用程序。一切正常,我可以收到一个令牌,用它来验证和所有的东西。现在我正在为Angular2开发应用程序的前端。
这里的主要问题是:如何在我的Oauth2安全配置中允许CORS? 我已经设法在我的Controller类中使用 @CrossOrigin 注释,但它在安全配置中如何工作?
我试过这个:
@Configuration
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/oauth/token").permitAll()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
但我仍然有错误:
否'访问控制 - 允许 - 来源'标头出现在请求的资源上。起源' http://localhost:3000'因此不允许访问。响应的HTTP状态代码为401。
答案 0 :(得分:-1)
根据Spring文档,CorsConfigurationSource
未用作bean,但在CorsFilter
中,请参阅https://docs.spring.io/spring/docs/current/spring-framework-reference/html/cors.html#_filter_based_cors_support
public class MyCorsFilter extends CorsFilter {
public MyCorsFilter() {
super(configurationSource());
}
private static UrlBasedCorsConfigurationSource configurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://domain1.com");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}
另一种方法是在WebMvcConfigurerAdapter
中提供cors映射,请参阅https://docs.spring.io/spring/docs/current/spring-framework-reference/html/cors.html#_javaconfig
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://domain2.com")
.allowedMethods("PUT", "DELETE")
.allowedHeaders("header1", "header2", "header3")
.exposedHeaders("header1", "header2")
.allowCredentials(false).maxAge(3600);
}
}