Spring SecurityFilterChain 403错误求助:Spring6.1+Vue3 JWT认证配置问题
问题分析与解决方法
常见原因及对应修复方案
1. 跨域请求(CORS)未配置
Vue前端和Spring后端通常运行在不同端口(比如前端8080、后端8081),跨域预检请求(OPTIONS)会被Spring Security拦截,即便你配置了允许访问的URL,也会返回403。
解决方法:
在SecurityConfig中添加CORS配置,同时确保Spring MVC层面开启CORS:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // 开启CORS并绑定自定义配置 .cors(cors -> cors.configurationSource(corsConfigurationSource())) .authorizeHttpRequests(auth -> auth .requestMatchers("/", "/login", "/signup").permitAll() .anyRequest().authenticated() ) // 前后端分离场景下通常关闭CSRF .csrf(csrf -> csrf.disable()); return http.build(); } // 自定义CORS规则 @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(Collections.singletonList("http://localhost:8080")); // 替换为你的前端地址 config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS")); config.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type")); config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; }
2. 请求匹配顺序错误
Spring Security的规则是从上到下匹配,如果anyRequest().authenticated()放在允许规则前面,会导致所有请求都要求认证,直接覆盖前面的permitAll规则。
错误示例:
// 错误:先匹配anyRequest,后续permitAll不会生效 .authorizeHttpRequests(auth -> auth .anyRequest().authenticated() .requestMatchers("/", "/login", "/signup").permitAll() )
正确顺序:
.authorizeHttpRequests(auth -> auth .requestMatchers("/", "/login", "/signup").permitAll() .anyRequest().authenticated() )
3. URL匹配不准确
如果实际请求的URL带有上下文路径(比如应用部署在/api下),或者前端请求的是/api/login但你配置的是/login,会导致规则不匹配,触发403。
解决方法:
- 核对前端请求的实际URL,确保与
requestMatchers配置的路径完全一致 - 若有上下文路径,可调整配置为
requestMatchers("/api/", "/api/login", "/api/signup")
4. CSRF防护拦截请求
Spring Security默认开启CSRF防护,对于POST、PUT等修改类请求,需要携带CSRF令牌。前后端分离场景下通常无需CSRF,直接关闭即可。
解决方法:
在SecurityFilterChain中添加:
.csrf(csrf -> csrf.disable())
5. 控制器权限注解冲突
如果你的LoginController或SignupController上标注了@PreAuthorize("isAuthenticated()")这类权限注解,会覆盖SecurityFilterChain的permitAll配置,导致403。
解决方法:
检查控制器类或方法上的权限注解,移除不必要的@PreAuthorize、@Secured等注解。
内容的提问来源于stack exchange,提问作者ROME
相关产品推荐
相关产品推荐

