【问题标题】:Why Spring Security did not add Access-Control-Allow-Origin for GET request with a Request Header?为什么 Spring Security 没有为带有请求标头的 GET 请求添加 Access-Control-Allow-Origin?
【发布时间】:2021-04-19 08:17:41
【问题描述】:

我的目标是调试为什么我可以在没有RequestHeaders 的情况下发送 HTTP GET 请求,但我无法在浏览器上使用RequestHeaders 发送 HTTP GET 请求。

我正在关注spring.io's tutorial 以了解有关 CSRF 和 CORS 的更多信息。

我尝试过的:

  1. 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.
  1. 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/…有帮助

标签: java angular spring cors


【解决方案1】:

如果你使用 JDK 8+,有一个解决方案:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
}

让我知道这是否有效。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-03
  • 1970-01-01
  • 2017-02-07
  • 2016-08-03
  • 2023-03-16
  • 2014-07-30
  • 2016-01-14
相关资源
最近更新 更多