Spring Security下Vue前端请求遇CORS跨域问题求助
解决Spring Security与Vue跨域CORS问题
当Vue前端通过Axios请求Spring Security表单接口时出现CORS错误,核心原因是Spring Security的过滤器优先级高于CORS过滤器,导致预检请求(OPTIONS)被拦截。需要在Security配置中直接集成CORS策略,具体修改如下:
步骤1:修改Spring Security配置类
在你的WebAuthorization类中新增CORS配置Bean,并在Security过滤器链中启用CORS:
import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.cors.CorsConfigurationSource; import java.util.Arrays; @EnableWebSecurity @Configuration public class WebAuthorization { // 定义CORS跨域规则 @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); // 替换为你的Vue前端实际域名,例如http://localhost:8080 config.setAllowedOrigins(Arrays.asList("http://localhost:8080")); // 允许的HTTP请求方法 config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); // 允许的请求头,覆盖表单登录所需的内容类型 config.setAllowedHeaders(Arrays.asList("Content-Type", "X-Requested-With")); // 允许携带Cookie(如JSESSIONID),保证表单登录会话有效 config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // 对所有接口应用CORS规则 source.registerCorsConfiguration("/**", config); return source; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // 先启用CORS,确保CORS过滤器优先于Security认证过滤器执行 http.cors(cors -> cors.configurationSource(corsConfigurationSource())) .formLogin(form -> form .usernameParameter("email") .passwordParameter("password") .loginPage("/api/login")) .logout(logout -> logout .logoutUrl("/api/logout") .deleteCookies("JSESSIONID")); return http.build(); } }
步骤2:配置前端Axios
确保Vue的Axios请求开启withCredentials,否则Cookie无法跨域传递:
// 示例登录请求配置 axios.post('/api/login', { email: 'your-email', password: 'your-password' }, { withCredentials: true })
补充说明
- 若需允许多个前端域名,可使用
setAllowedOriginPatterns替代setAllowedOrigins,例如:config.setAllowedOriginPatterns(Arrays.asList("http://*.yourdomain.com", "http://localhost:*")); - 若前端仍出现CSRF错误,可在前后端分离场景下关闭CSRF:
http.csrf(csrf -> csrf.disable())
内容的提问来源于stack exchange,提问作者Sebastián valbuena
相关产品推荐
相关产品推荐

