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

Spring Boot应用动态子域名CORS文件上传问题求助

解决Spring Boot中动态子域名的CORS文件上传问题

问题分析

你的配置中已添加*.mydomain2.app作为允许的源模式,但动态子域名(如https://care-upload.mydomain2.app)仍触发CORS错误,核心原因是源模式缺少协议前缀,导致Spring无法匹配带HTTPS的请求源;另外需排查Spring Security集成、部署环境配置等潜在冲突。

解决方案

1. 修正允许的源模式

将*.mydomain2.app修改为https://*.mydomain2.app,确保模式匹配完整的请求源(包含HTTPS协议):

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
public class CorsConfig {

    @Bean(name = "corsConfigurationSource")
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOriginPatterns(Arrays.asList(
                "http://localhost:4200",
                "https://mydomain1.com",
                "https://mydomain2.dev",
                "https://admin.mydomain2.app",
                "https://*.mydomain2.app" // 修正:添加HTTPS协议前缀
        ));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowCredentials(true);
        // 当allowCredentials为true时,建议明确指定允许的头部(部分浏览器对*的支持有限)
        configuration.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization", "X-Requested-With"));
        // 暴露文件上传可能需要的响应头部(如返回的文件地址Location)
        configuration.setExposedHeaders(Arrays.asList("Location"));

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

2. 集成Spring Security(若使用)

如果项目依赖Spring Security,必须在安全配置中显式启用CORS,否则自定义的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.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfigurationSource;

@Configuration
public class SecurityConfig {

    private final CorsConfigurationSource corsConfigurationSource;

    public SecurityConfig(CorsConfigurationSource corsConfigurationSource) {
        this.corsConfigurationSource = corsConfigurationSource;
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .cors(cors -> cors.configurationSource(corsConfigurationSource)) // 绑定自定义CORS配置
                .csrf(csrf -> csrf.disable()) // 文件上传场景通常需关闭CSRF,或配置前端传递CSRF令牌
                .authorizeHttpRequests(auth -> auth
                        .requestMatchers("/apis/v1/staff/uploadImage/**").permitAll() // 根据实际权限调整
                        .anyRequest().authenticated()
                );
        return http.build();
    }
}

3. 排查配置冲突

  • 检查application.properties/application.yml中是否存在spring.web.cors.*相关全局配置,这类配置会覆盖自定义的CorsConfigurationSource Bean,需删除或统一配置逻辑。
  • 确认项目中没有其他自定义CORS过滤器或拦截器,避免重复处理导致响应头丢失。

4. 验证预检请求

使用curl发送OPTIONS预检请求,验证响应头是否包含正确的CORS信息:

curl -X OPTIONS https://backend.care-upload.mydomain2.app/apis/v1/staff/uploadImage/1 \
  -H "Origin: https://care-upload.mydomain2.app" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: Content-Type"

正常响应应包含以下关键头部:

Access-Control-Allow-Origin: https://care-upload.mydomain2.app
Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS
Access-Control-Allow-Credentials: true

5. 检查部署环境配置

若使用GCP负载均衡、Cloud Run等服务,需确认平台层面的CORS配置:

  • 如果GCP侧已配置CORS规则,需与Spring的配置保持一致,避免冲突;
  • 确保代理服务未修改或过滤Origin请求头,保证完整传递到Spring后端。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 03:27:33