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

Spring Boot资源服务调用出现No 'access-control-allow-origin' CORS错误如何解决

问题根因

你遇到的CORS异常本质是Spring Security OAuth2 资源服务器的过滤器链优先级高于普通WebSecurity配置链,导致你之前配置的CORS规则未生效:

  • 加了@EnableResourceServer的资源服务器默认优先级为Ordered.HIGHEST_PRECEDENCE,你所有受权限保护的接口都会先走资源服务器的过滤器链
  • 浏览器发起跨域请求前会先发送不带Authorization头的OPTIONS预检请求,该请求会直接被资源服务器拦截返回401,根本不会走到你配置的MVC跨域规则、Controller的@CrossOrigin注解,因此响应里不会携带Access-Control-Allow-Origin头,触发CORS报错

解决方案

按以下步骤修改配置即可解决:

1. 补全资源服务器的CORS和预检请求放行规则

修改你的ResourceServerConfig类,重写configure(HttpSecurity http)方法,显式开启CORS并放行所有OPTIONS预检请求:

import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.http.SessionCreationPolicy;

@Configuration
@EnableResourceServer
@EnableConfigurationProperties(SecurityProperties.class)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                // 放行所有OPTIONS预检请求
                .authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                // 原有资源服务器的其他权限规则保留即可
                .anyRequest().authenticated()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    // 注册全局CORS配置Bean,资源服务器的cors()会自动读取该配置
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // 测试环境可填*,生产环境建议换成前端具体域名(如http://localhost:3000)
        configuration.addAllowedOrigin("*");
        configuration.addAllowedMethod("*");
        configuration.addAllowedHeader("*");
        // 若不需要跨域传递Cookie可注释该行
        // configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

注意:如果开启setAllowCredentials(true),则allowedOrigin不能使用*,必须填写前端服务的具体地址,否则会触发新的CORS错误。

2. 清理冗余的CORS配置避免冲突

  • 删除Controller类上的@CrossOrigin注解
  • 删除你之前写的CrossConfig跨域配置类
  • 保留WebSecurityConfig里的http.cors()配置即可,不需要额外修改

验证方式

修改完成后重启Spring Boot服务,清空浏览器缓存重新发起请求即可正常访问。

内容的提问来源于stack exchange,提问作者Nafaz M N M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:48:03