如何解决Spring Boot+MSAL与Angular集成时出现的CORS policy拦截错误
Spring Boot 集成 MSAL (Azure AD) 时 CORS 预检请求失败解决方案
核心问题原因
MSAL 自带的 SecurityConfig 优先级默认高于自定义的配置类,你之前设置的 @Order(3) 优先级不够高,MSAL 的过滤器链会先拦截所有请求,包括 CORS 预检的 OPTIONS 请求,导致你自定义的放行规则和接口 @CrossOrigin 注解不会生效。
分步解决步骤
- 第一步:调整自定义 SecurityConfig 的优先级,设置为比 MSAL 配置类更高的优先级(数字越小优先级越高),修改注解为
@Order(1) - 第二步:在自定义 SecurityConfig 中明确配置 CORS 全局规则,同时优先放行所有 OPTIONS 请求,示例配置代码如下:
@Configuration @Order(1) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http // 优先配置CORS .cors().configurationSource(corsConfigurationSource()) .and() .authorizeRequests() // 放行所有OPTIONS预检请求 .antMatchers(HttpMethod.OPTIONS).permitAll() // 其他原有权限规则保持不变 .anyRequest().authenticated() .and() // 原有MSAL资源服务器配置保持不变 .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); } // 全局CORS配置 private CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); // 允许的前端地址,生产环境替换为实际域名 configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200")); configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); configuration.setAllowedHeaders(Arrays.asList("*")); // 允许携带认证信息(token等) configuration.setAllowCredentials(true); // 预检请求缓存时间,减少重复预检请求 configuration.setMaxAge(3600L); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } }
注:如果你使用的是 Spring Boot 2.7+ 版本,
WebSecurityConfigurerAdapter已废弃,改用注册SecurityFilterChainBean 的方式编写配置即可,CORS 配置规则保持一致。
- 第三步:移除接口上单独加的
@CrossOrigin注解,避免和全局配置冲突 - 第四步:不需要修改 MSAL 自带的配置类,只要自定义配置优先级更高即可正常生效。
验证逻辑
启动项目后发送 OPTIONS 请求到你的接口地址,检查响应头是否包含 Access-Control-Allow-Origin: http://localhost:4200、Access-Control-Allow-Credentials: true 字段,确认预检请求返回200状态码即可。
内容的提问来源于stack exchange,提问作者user3760894
相关产品推荐
相关产品推荐

