【发布时间】:2021-04-19 08:17:41
【问题描述】:
我的目标是调试为什么我可以在没有RequestHeaders 的情况下发送 HTTP GET 请求,但我无法在浏览器上使用RequestHeaders 发送 HTTP GET 请求。
我正在关注spring.io's tutorial 以了解有关 CSRF 和 CORS 的更多信息。
我尝试过的:
- 向
http://localhost:8080/user发送带有请求标头Authorization: Basic .....的GET 请求会返回CORS 错误
Access to XMLHttpRequest at 'http://localhost:8080/user' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
- 向
http://localhost:8080/user发送没有请求标头的 GET 请求不会返回 CORS 错误。
注意:如果我没有添加请求标头,我会仔细检查任何 GET 请求的 CORS 问题是否已解决。
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Collections.singletonList("http://localhost:4200"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
但是,如果我发送带有请求标头 Authorization: Basic .... 的 GET /user,它并不能解决 CORS 问题
我的预期结果是:当我发送带有请求标头的 GET 请求时,它不应该返回 CORS 错误。
我的实际结果是:它返回一个 CORS 错误。
【问题讨论】:
-
您对“授权”和公共 URL 有不同的配置吗?
-
@gvmani 我只覆盖
WebSecurityConfigurerAdapter类中的configure(HttpSecurity http)方法。 Angular 项目和 Spring Security 项目位于不同的端口。请随意克隆the full repository。 -
这个问题可能对stackoverflow.com/questions/36968963/…有帮助