Spring Security与Vue.js集成CORS配置403错误排查
排查Vue+Spring登录API的CORS 403问题
出现Cross-Origin Request Blocked且状态码403,核心原因是Spring Security的过滤器链优先级高于Controller的@CrossOrigin注解,导致请求被Security拦截时,CORS响应头还未被设置。以下是具体排查和解决步骤:
1. 修正Spring Security的CORS配置(关键)
Security的CORS配置必须在过滤器链中优先启用,且要确保登录接口允许匿名访问,否则未登录请求会直接被拦截返回403,CORS头无法生效。示例配置:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http // 必须将CORS配置放在最前面,确保过滤器优先级最高 .cors().and() // 前后端分离场景先临时关闭CSRF测试,后续按需配置 .csrf().disable() .authorizeRequests() // 登录接口必须允许匿名访问,否则OPTIONS预检和登录请求都会被拦截 .antMatchers("/api/login").permitAll() .anyRequest().authenticated(); } // 全局CORS配置Bean @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); // 指定允许的前端源 config.setAllowedOrigins(Arrays.asList("http://localhost:8081")); // 允许所有HTTP方法,包括OPTIONS预检请求 config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); // 允许所有请求头 config.setAllowedHeaders(Arrays.asList("*")); // 如果前端需要携带Cookie,必须开启此项,前端也要对应配置withCredentials config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // 对所有接口应用CORS规则 source.registerCorsConfiguration("/**", config); return source; } }
2. 移除Controller上的@CrossOrigin注解
全局Security CORS配置与Controller注解可能存在冲突,且注解优先级低于Security过滤器,直接删除@CrossOrigin("http://localhost:8081"),用全局配置统一处理。
3. 检查前端axios配置
如果后端开启了allowCredentials,前端必须对应开启携带凭证的配置:
// 全局配置axios axios.defaults.withCredentials = true; // 或者单独在登录请求中设置 axios.post('http://localhost:8080/api/login', formData, { withCredentials: true })
4. 验证OPTIONS预检请求
用Postman手动发送OPTIONS请求到http://localhost:8080/api/login,查看响应头是否包含Access-Control-Allow-Origin: http://localhost:8081。如果存在,说明CORS配置生效;如果不存在,检查Security配置的过滤器顺序是否正确,是否有自定义过滤器提前拦截了请求。
内容的提问来源于stack exchange,提问作者MC_Vovi
相关产品推荐
相关产品推荐

