我有一个Spring Boot rest api服务器,我正在尝试通过Vue.js应用程序连接到它
这是我配置Spring Boot Security的方式
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;
}
}
当我尝试从客户端访问授权令牌时,在OPTIONS请求上出现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.
我不知道还应该设置什么
答案 0 :(得分:0)
您肯定应该在"*"
中使用"/**"
而不是setAllowedOrigins
。
配置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");
}
}
另请参阅CorsRegistration javadoc和Setting up CORS in Spring Boot tutorial