【问题标题】:Spring Authorization Server: Access to XMLHttpRequest has been blocked by CORS policySpring 授权服务器:对 XMLHttpRequest 的访问已被 CORS 策略阻止
【发布时间】:2023-01-23 06:07:31
【问题描述】:

我有一个基本的 Spring 授权服务器设置为 Spring Boot 应用程序。我正在尝试使用 angular-auth-oidc-client 通过角度应用程序访问此服务器。

当我尝试登录时,出现此错误:

Access to XMLHttpRequest at 'http://localhost:9000/mydomain/.well-known/openid-configuration' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我已多次尝试解决此问题,但均未成功。

授权服务器配置的相关部分如下:


    // @formatter:off
    @Bean
    public RegisteredClientRepository registeredClientRepository() {
        
        // removed

    }
    // @formatter:on

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Arrays.asList("*"));
        config.setAllowedMethods(Arrays.asList("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH"));
        config.setAllowedHeaders(Arrays.asList("*"));
        config.setAllowCredentials(true);

        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("POST");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        return source;
    }   

    // @formatter:off
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SecurityFilterChain authServerSecurityFilterChain(HttpSecurity http) throws Exception {
        
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        http
            .formLogin(Customizer.withDefaults())
            .cors().configurationSource(corsConfigurationSource());
        
        return http.build();
    }
    // @formatter:on

该 CORS 配置似乎很开放,但我仍然看到问题。

我只是犯了一个我没有看到的愚蠢错误吗?

编辑:是的,我已经在 application.yml 中配置了该端口和域:

server:
  port: 9000
  servlet:
    context-path: /mydomain

【问题讨论】:

  • 确保你有正确的导入(有两个CorsConfigurationSource):import org.springframework.web.cors.CorsConfigurationSource;。请参阅this commit,了解我为使其正常工作而添加的内容。 (注意:这是一个较旧的分支)
  • 另请参阅related webinar,我们在其中演示了上述分支。
  • 不,我肯定使用你提到的那个,而不是反应式的。
  • 我复制了您的 CorsConfiguration 和设置,现在我处于重定向循环中。我想这就是进步,但进步的方向还悬而未决。
  • 您是否已将 .cors() 添加到两个过滤器链?

标签: spring-boot spring-security spring-authorization-server


【解决方案1】:

我正在使用 Angular UI 在生产环境中测试它并看到相同的结果。 openid 的 CORS 设置似乎不清楚。有没有人有最新的 Spring Authorization Server 1.0.0 或更高版本的示例?

enter image description here

enter image description here

【讨论】:

    猜你喜欢
    • 2019-12-18
    • 2022-08-14
    • 2020-05-05
    • 2020-03-12
    • 2019-09-16
    • 2019-04-28
    • 2021-10-27
    • 2019-09-23
    相关资源
    最近更新 更多