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

Spring Boot 3.2.5 REST API缺失Access-Control-Allow-Origin头求助

Spring Boot 3.2.5 CORS配置不生效排查方案

1. 确认全局CORS配置的正确性

Spring Boot 3.x的全局CORS配置写法有细节要求,别用旧版本的写法,以下是标准配置:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOriginPatterns("*") // 3.x推荐用这个替代allowedOrigins,支持带凭证的通配符
                        .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                        .allowedHeaders("*")
                        .allowCredentials(true);
            }
        };
    }
}

如果你的项目集成了Spring Security,这个配置会被Security的规则覆盖,必须单独配置Security的CORS。

2. Spring Security环境下的CORS配置

这是绝大多数人踩坑的点:Spring Security优先级高于WebMvc的CORS配置,必须显式在SecurityFilterChain中启用CORS:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.List;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .cors(cors -> cors.configurationSource(corsConfigurationSource())) // 必须启用CORS
                .csrf(csrf -> csrf.disable()) // 若不需要CSRF可禁用,否则需配置允许的请求
                .authorizeHttpRequests(auth -> auth
                        .anyRequest().permitAll()
                );
        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOriginPatterns(List.of("*")); // 替换为实际允许的客户端地址
        configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(List.of("*"));
        configuration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

3. @CrossOrigin注解的使用细节

  • 确保注解加在控制器类或具体接口方法上,不要漏加
  • 如果开启allowCredentials=true,不能用origins="*",必须指定具体的客户端地址(比如Flutter运行的http://localhost:5173)
  • 示例:
@RestController
@CrossOrigin(origins = "http://localhost:5173", allowedHeaders = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class DemoController {
    // 接口实现
}

4. 正确用curl测试CORS头

CORS相关响应头只有在跨域请求(即请求携带Origin头且与服务器地址不同)时才会返回。直接用curl请求不带Origin头是看不到的,正确测试命令:

curl -H "Origin: http://localhost:5173" -v http://你的服务器地址/api/xxx

5. 排查自定义过滤器的影响

如果项目中有自定义Filter,要确保它不会修改或移除CORS相关响应头,且过滤器执行顺序在CORS过滤器之前。可以在过滤器中添加日志,检查响应头是否被正确设置。


内容的提问来源于stack exchange,提问作者vogella

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 05:45:13