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

接入Spring Security后Angular请求Spring Boot接口被CORS拦截如何解决

Spring Boot引入Spring Security后CORS跨域失效解决方案

引入Spring Security后出现跨域问题的核心原因是Spring Security过滤器链优先级高于Spring MVC层的过滤器链,前端发送的CORS预检OPTIONS请求未到Web MVC层就被Spring Security拦截,未返回对应的跨域头,导致浏览器报错。

步骤1:在Spring Security配置中开启CORS支持

根据你使用的Spring Security版本选择对应配置:

  • 若使用低于5.7版本(仍使用WebSecurityConfigurerAdapter),在安全配置类的configure(HttpSecurity http)方法中添加.cors()配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 开启CORS支持,Spring Security会自动加载已配置的跨域规则
            .cors().and()
            // 以下为你原有安全配置,保留即可
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .httpBasic();
    }
}
  • 若使用5.7及以上版本(WebSecurityConfigurerAdapter已废弃),在SecurityFilterChain Bean配置中开启CORS:
@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            // 开启CORS默认处理
            .cors(Customizer.withDefaults())
            // 以下为你原有安全配置,保留即可
            .authorizeHttpRequests(auth -> auth
                .anyRequest().authenticated()
            );
        return http.build();
    }
}

步骤2:统一配置跨域规则(可选,更稳妥)

你可以保留原有WebMvcConfigurer的跨域配置,也可以直接声明CorsConfigurationSource Bean,供Spring Security和Web MVC共用,避免配置不一致问题:

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration config = new CorsConfiguration();
    // 允许的前端地址,不要用*同时开启凭证传输
    config.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
    // 允许的请求方法
    config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    // 允许的请求头
    config.setAllowedHeaders(Arrays.asList("*"));
    // 允许携带凭证(如Cookie、Authorization头)
    config.setAllowCredentials(true);
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    return source;
}

注意事项

  • 不要同时配置setAllowedOrigins("*")和setAllowCredentials(true),Spring Boot 2.4+版本会直接拒绝该无效配置。
  • 开启cors()后Spring Security默认会放行所有OPTIONS请求,无需手动给OPTIONS请求配置permitAll。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 09:45:05