You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

配置Spring Security CORS头后仍出现Access-Control-Allow-Origin缺失问题

CORS跨域拦截问题求助

遇到如下CORS拦截错误:

Access to XMLHttpRequest at 'https:xyztest.com/as/authorization.oauth2?client_id=newpeteGAQA&redirect_uri=http://localhost:8080/login&response_type=code&scope=openid%20profile&state=B2Rig4' 
(redirected from 'http://localhost:8080/health-incidents') from origin 'http://localhost:8081' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.
newrelic.js:1          GET https://testxyz.com/as/authorization.oauth2?client_id=newpeteGAQA&redirect_uri=http://localhost:8080/login&response_type=code& 

已尝试在Spring Security配置中添加响应头,但问题依旧,配置代码如下:

protected void configure(HttpSecurity http) throws Exception {
        if (enableAuthentication && !unsecured) {
            http
                    .csrf().disable()
                    .headers(headers ->
                            headers
                                    .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Origin","http://localhost:8081"))
                                    .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Methods","POST, PUT, GET, OPTIONS, DELETE"))
                                    .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Credentials","true"))
                                   // .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Headers","Authorization, Content-Type"))
                                    .addHeaderWriter( new StaticHeadersWriter("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, X-Requested-With, remember-me"))
                               //     .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Origin", "*"))
                    )
                    .antMatcher(ANY_PATH).authorizeRequests()

                    .antMatchers(whitelist).permitAll()
                    .anyRequest().authenticated()
                    .and().addFilterAfter(oauth2SsoFilter(), HeaderWriterFilter.class)
                    .logout()
                    .logoutSuccessUrl("/login")
                    .invalidateHttpSession(true)
                    .deleteCookies("SESSION");
            addAuthenticationEntryPoint(http);
        } else {
            http
                    .csrf().disable()
                    .antMatcher(ANY_PATH).authorizeRequests()
                    .antMatchers(ANY_PATH).permitAll();
        }
    }

请问还需排查哪些配置或进行哪些修改?


排查与修改建议
  • 确认CORS头的作用对象:错误提示中被拦截的请求目标是https://xyztest.com/as/authorization.oauth2,这是授权服务器的地址。你当前在自己应用中配置的CORS头,只会作用于自身服务的响应,无法影响授权服务器的响应。需要在授权服务器端配置允许http://localhost:8081的跨域请求。

  • 放行OPTIONS预检请求:浏览器对非简单请求会发送OPTIONS预检,当前配置未明确放行这类请求。需在白名单中添加OPTIONS方法:

    .antMatchers(HttpMethod.OPTIONS, whitelist).permitAll()
    

    或者全局放行所有OPTIONS请求,避免预检被拦截。

  • 改用Spring Security原生CORS配置:放弃手动添加StaticHeadersWriter,使用框架内置的CORS配置,它能自动处理预检请求和头的正确注入:

    http.cors(cors -> cors.configurationSource(request -> {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Collections.singletonList("http://localhost:8081"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "X-Requested-With", "remember-me"));
        config.setAllowCredentials(true);
        return config;
    }))
    
  • 检查白名单覆盖范围:确认/health-incidents路径是否在whitelist中,如果不在,请求会被拦截进入认证流程,导致CORS头无法正常添加到响应中。

  • 排查过滤器优先级与覆盖问题:若应用中有其他过滤器(自定义或第三方),可能会覆盖你设置的CORS头。通过浏览器开发者工具查看实际响应头,确认Access-Control-Allow-Origin是否存在,或被其他值覆盖。

内容的提问来源于stack exchange,提问作者Rav Singh Sandhu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 07:46:00