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

Spring Boot如何按环境动态配置CORS源以移除生产环境localhost地址

Spring Boot 多环境自动切换 CORS 配置方案

Spring Boot 自带的 Profile 机制可以完美实现你要的配置自动切换效果,不需要手动修改代码,和前端切换环境配置的逻辑一致,实现步骤如下:

1. 基于 Environment 环境判断实现逻辑

首先在你的 WebSecurityConfig 类中注入 Environment 实例,在 CORS 配置方法中判断当前环境是否为生产环境,动态拼接允许源列表:

import org.springframework.core.env.Environment;
import org.springframework.beans.factory.annotation.Autowired;

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private Environment env;

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // 初始化通用允许域名列表
        List<String> allowedOrigins = new ArrayList<>(Arrays.asList(
            // 这里放你固定的业务域名,比如生产、测试环境的正式域名
            "https://your-official-domain.com",
            "https://test.your-domain.com"
        ));
        // 非生产环境自动加入本地调试地址
        if (!Arrays.asList(env.getActiveProfiles()).contains("prod")) {
            allowedOrigins.add("http://localhost:4200/");
        }
        configuration.setAllowedOrigins(allowedOrigins);
        
        configuration.addAllowedHeader("Authorization");
        configuration.addAllowedHeader("Content-Type");
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

2. 配置环境激活规则

你可以通过两种方式切换环境,不需要修改代码:

  • 配置文件区分:在 resources 目录下新建对应环境的配置文件,比如 application-prod.yml(生产配置)、application-dev.yml(开发配置)
  • 启动参数指定:启动服务时通过参数指定激活的环境:
    • 本地开发:IDE 启动参数加 --spring.profiles.active=dev 或者不配置,默认不会激活prod环境
    • 生产部署:启动命令为 java -jar your-app.jar --spring.profiles.active=prod,此时自动过滤掉localhost的允许源

3. 可选:使用@Profile注解实现配置完全隔离

如果你希望生产和开发的CORS配置完全隔离,也可以用@Profile注解分别注册不同环境的CORS Bean:

@Bean
@Profile("prod")
CorsConfigurationSource prodCorsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList(
        "https://your-official-domain.com"
    ));
    configuration.addAllowedHeader("Authorization");
    configuration.addAllowedHeader("Content-Type");
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

@Bean
@Profile("!prod")
CorsConfigurationSource devCorsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList(
        "https://test.your-domain.com",
        "http://localhost:4200/"
    ));
    configuration.addAllowedHeader("Authorization");
    configuration.addAllowedHeader("Content-Type");
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

注意:两种方案都不需要重复打包应用,仅启动时指定不同的环境参数即可,可以直接集成到CI/CD流程中,完全不需要手动修改代码调整CORS列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:06:03