Spring boot Spring启动-无法配置CORS选项策略
我有一个SpringBootRESTAPI服务器,我正试图通过Vue.js应用程序连接到它 这就是我如何配置Spring引导安全性的方法Spring boot Spring启动-无法配置CORS选项策略,spring-boot,cors,Spring Boot,Cors,我有一个SpringBootRESTAPI服务器,我正试图通过Vue.js应用程序连接到它 这就是我如何配置Spring引导安全性的方法 public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http. .....
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.
.....
.cors()
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("/**"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
当我尝试从客户端访问授权令牌时,我在选项请求上收到一个403错误
Access to XMLHttpRequest at 'http://localhost:8081/oauth/token' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我不知道我还应该设置什么您肯定应该在
中设置“*”
而不是“/**”
配置CORS AFAIK的正确方法还有:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
.allowedHeaders("authorization", "content-type", "x-auth-token")
.exposedHeaders("x-auth-token");
}
}
另请参见和问题不在于您的CORS配置。问题是您的服务器正在使用403 to for OPTIONS请求响应http://localhost:8081/oauth/token
。您需要将该服务器配置为使用200 OK响应该URL的选项请求。