You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Security 403问题:配置JWT与角色后请求始终被禁止

问题排查与解决方案

1. Spring Security 默认规则拦截未匹配请求

你的配置仅开放了/api/users/**路径,但未对其他路径做明确规则定义。Spring Security 在未指定anyRequest()规则时,默认会拒绝所有未匹配的请求(等效于anyRequest().denyAll()),这是导致非/api/users/**路径返回403的核心原因之一。

解决办法:

  • 若需开放所有路径,补充anyRequest().permitAll():
.authorizeHttpRequests((requests) -> requests
        .requestMatchers("/api/users/**").permitAll()
        .anyRequest().permitAll() // 新增该行
)
  • 若仅开放特定路径,确保所有需要访问的接口路径都被requestMatchers覆盖。

2. CORS 预检请求被拦截

你使用了.cors(Customizer.withDefaults()),但默认CORS配置仅允许同源请求。Postman发起的跨域请求会先发送OPTIONS预检请求,Spring Security可能拦截该请求返回403。

解决办法:
自定义CORS配置,允许跨域请求:

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*")); // 生产环境建议替换为具体允许的域名
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type"));
    configuration.setAllowCredentials(true);

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

然后在SecurityFilterChain中替换默认CORS配置:

http
    .cors(cors -> cors.configurationSource(corsConfigurationSource()))
    // ...其他原有配置

3. JWT过滤器的潜在问题(当前已注释,后续启用需修复)

你的JWTFilter中extractToken方法存在逻辑错误:读取了Authorization请求头但直接返回null,导致永远无法提取令牌。修复代码如下:

private String extractToken(HttpServletRequest request) {
    String authHeader = request.getHeader("Authorization");
    if (authHeader != null && authHeader.startsWith("Bearer ")) {
        return authHeader.substring(7); // 移除"Bearer "前缀,获取纯令牌内容
    }
    return null;
}

另外,过滤器中捕获JWTVerificationException后无任何处理,建议添加日志记录或返回401响应,便于后续排查令牌验证失败问题。


内容的提问来源于stack exchange,提问作者Bartolinio Kooperinio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 16:25:06