SpringBoot OAuth2对接React请求/oauth/token出现CORS预请求错误如何解决
根因分析
Spring Security过滤器链优先级高于普通的Web MVC CORS配置,OAuth2内置的/oauth/token端点默认会拦截所有未认证请求,包括预检用的OPTIONS请求,直接返回非200状态码,所以就算加了@CrossOrigin和基础的http.cors()配置还是会触发CORS错误。
排查步骤
- 首先确认
@CrossOrigin注解是否加在了错误的位置:/oauth/token是OAuth2框架内置端点,并非自定义Controller接口,加在自定义Controller上的@CrossOrigin注解对该接口完全不生效。 - 验证OPTIONS请求是否被安全框架拦截:用curl工具发送OPTIONS请求到
http://localhost:8000/oauth/token,如果返回401/403状态码即可确认是该问题。 - 检查全局CORS配置的路径覆盖范围:确认CORS规则是否包含
/oauth/**路径,避免只覆盖了业务接口路径。
解决方案
1. 配置安全规则放行OPTIONS请求
在Spring Security配置类中添加OPTIONS请求放行规则,同时显式配置覆盖所有端点的全局CORS规则,示例代码如下:
import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // 启用CORS并绑定自定义配置 .cors().configurationSource(corsConfigurationSource()) .and() .authorizeHttpRequests(auth -> auth // 放行所有OPTIONS预检请求 .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 放行令牌端点的直接请求 .requestMatchers("/oauth/token").permitAll() .anyRequest().authenticated() ) // 客户端模式调用接口不需要csrf校验,可以关闭 .csrf().disable(); return http.build(); } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); // 生产环境请替换为实际前端域名,不要使用通配符* config.addAllowedOrigin("http://localhost:3000"); config.addAllowedMethod("*"); config.addAllowedHeader("*"); config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // 所有路径都应用该CORS规则,覆盖OAuth2内置端点 source.registerCorsConfiguration("/**", config); return source; } }
2. 适配Spring Authorization Server场景
如果你使用的是新版Spring Authorization Server实现OAuth2服务,需要额外在授权服务器的过滤器链中添加相同的CORS配置,避免授权服务器的过滤器拦截预检请求。
验证方法
配置完成重启后端服务后,先发送OPTIONS请求到/oauth/token接口,确认返回200状态码,且响应头中包含Access-Control-Allow-Origin: http://localhost:3000,再从React端发送令牌请求即可正常获取响应。
内容的提问来源于stack exchange,提问作者Prakash Adhikari
相关产品推荐
相关产品推荐

