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

配置CORS允许所有源时登录报错的问题求助

解决CORS配置允许所有源但预检请求报错的问题

问题根源

当你设置allowCredentials(true)(允许携带Cookie、HTTP认证信息这类凭证)时,浏览器的安全规则要求Access-Control-Allow-Origin响应头必须是具体的源地址,不能用*或.*这类通配符模式。你的配置同时启用了凭证支持和通配符源,导致预检请求返回的响应头不符合浏览器要求,因此触发报错。

解决方案

根据是否需要携带凭证,分两种情况处理:

情况1:不需要携带凭证

直接移除allowCredentials(true)配置,使用allowedOriginPatterns("*")即可允许所有源:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS");
    }
}

情况2:必须携带凭证

不能使用通配符,需要通过自定义CORS过滤器动态允许请求的源。这种方式可以在支持凭证的同时,兼容所有合法源:

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

@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        
        // 允许携带凭证
        config.setAllowCredentials(true);
        // 允许所有源模式(Spring会自动将请求的具体Origin填充到响应头)
        config.addAllowedOriginPattern("*");
        // 允许所有请求头
        config.addAllowedHeader("*");
        // 允许所有请求方法
        config.addAllowedMethod("*");
        // 暴露所有响应头(如果前端需要获取自定义响应头则需配置)
        config.addExposedHeader("*");
        
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

额外注意事项

如果项目中使用了Spring Security,需要在安全配置中开启CORS支持:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Autowired
    private CorsFilter corsFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 将CORS过滤器添加到Security过滤器链最前面
        http.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
                .cors().and()
                // 其他安全配置...
                .authorizeRequests()
                .anyRequest().authenticated();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:25:16