Angular 5应用调用Spring Security 4.2.3 OAuth2的/oauth/token端点CORS失效
解决Angular 5 + Spring Security 4.2的CORS预检请求失败问题
看起来你遇到的是典型的跨域预检(OPTIONS)请求被Spring Security拦截的问题,我帮你梳理下正确的配置方式,应该能解决这个问题:
首先,只在HttpSecurity里加.cors().and()是不够的,Spring Security需要明确的CORS规则配置才能正确处理OPTIONS请求。你需要自定义CorsConfigurationSource来指定允许的域名、请求方法和头信息,同时确保/oauth/token端点能被OPTIONS请求访问。
以下是完整的配置代码:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http // 关联自定义的CORS配置 .cors().configurationSource(corsConfigurationSource()).and() .csrf().disable() .anonymous().disable() .authorizeRequests() // 允许所有人访问token端点(包括OPTIONS预检请求) .antMatchers("/oauth/token").permitAll() // 其他接口需要认证 .anyRequest().authenticated(); } // 自定义CORS规则,适配你的Angular应用 private CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); // 替换成你的Angular应用域名,生产环境别用* config.setAllowedOrigins(Arrays.asList("http://localhost:4200")); // 允许的请求方法,必须包含OPTIONS config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); // 允许的请求头,token请求需要这些头 config.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type", "X-Requested-With")); // 如果你的应用需要携带cookie/凭证,开启这个 config.setAllowCredentials(true); // 预检请求的缓存时间,减少重复OPTIONS请求 config.setMaxAge(3600L); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // 对所有路径应用CORS规则 source.registerCorsConfiguration("/**", config); return source; } // 额外配置:让WebSecurity忽略OPTIONS请求的安全检查 @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers(HttpMethod.OPTIONS, "/oauth/token"); } }
几个关键注意点:
- 必须自定义
CorsConfigurationSource:Spring Security默认的CORS配置非常严格,不会自动允许你需要的头和方法,所以一定要手动指定。 - 确保OPTIONS请求能通过:通过
WebSecurity.ignoring()或者authorizeRequests().permitAll()让OPTIONS请求绕过Spring Security的拦截,这是预检请求成功的核心。 - 不要滥用
*:生产环境一定要把allowedOrigins设置为具体的前端域名,避免安全风险。 - 检查Angular请求头:确保你的登录请求携带了正确的
Content-Type: application/x-www-form-urlencoded,这是OAuth2 token请求的标准要求。
如果配置后还是有问题,可以打开Chrome的开发者工具,看Network面板里OPTIONS请求的响应头,确认Access-Control-Allow-Origin等CORS头是否正确返回。
内容的提问来源于stack exchange,提问作者aCiD
相关产品推荐
相关产品推荐

