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

已认证用户的SecurityContextHolder为何被设为Anonymous SecurityContext?

问题描述

我的目标是让Spring Cloud Gateway对接Keycloak完成认证后,将请求路由到客户端方法。目前Spring Cloud Gateway运行正常,用户已通过Keycloak完成认证,但客户端的SecurityContextHolder却被设置为Anonymous SecurityContext。

客户端安全链配置如下:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated())
                .oauth2ResourceServer((oauth2) -> oauth2.jwt(Customizer.withDefaults()));
        return http.build();
    }
}

相关日志片段:

2025-02-01 12:53:38.420 [,] DEBUG o.s.s.w.a.AnonymousAuthenticationFilter - Set SecurityContextHolder to anonymous SecurityContext
2025-02-01 12:53:38.422 [,] DEBUG o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor - Using 'text/html', given [text/html, application/xhtml+xml, image/avif, image/webp, image/apng, application/xml;q=0.9, */*;q=0.8, application/signed-exchange;v=b3;q=0.7] and supported [text/plain, */*, application/json, application/*+json]
2025-02-01 12:53:38.422 [,] DEBUG o.s.w.s.m.m.a.RequestResponseBodyMethodProcessor - Writing ["WebAuthenticationDetails [RemoteIpAddress=10.0.0.159, SessionId=null]      Scopes: [ROLE_ANONYMOUS]"]
解决方案

核心问题是网关未正确转发认证后的JWT令牌,或客户端无法解析令牌。按以下步骤修复:

  • 开启Gateway的令牌转发功能
    必须配置TokenRelay过滤器,让网关把Keycloak颁发的JWT令牌传递到下游客户端服务。
    Java配置方式:

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("client-service", r -> r.path("/client/**")
                        .filters(f -> f.tokenRelay())
                        .uri("http://localhost:8081"))
                .build();
    }
    

    YAML配置方式:

    spring:
      cloud:
        gateway:
          routes:
            - id: client-service
              uri: http://localhost:8081
              predicates:
                - Path=/client/**
              filters:
                - TokenRelay=
    
  • 配置客户端服务的JWT验证参数
    在客户端的application.yml中添加Keycloak的realm信息,确保能正确解析令牌:

    spring:
      security:
        oauth2:
          resourceserver:
            jwt:
              issuer-uri: http://{keycloak-host}:{port}/auth/realms/{your-realm}
              jwk-set-uri: http://{keycloak-host}:{port}/auth/realms/{your-realm}/protocol/openid-connect/certs
    

    同时确认客户端依赖中已包含spring-boot-starter-oauth2-resource-server。

  • 验证令牌转发是否生效
    在客户端添加请求日志或过滤器,检查请求头中是否存在Authorization: Bearer {token}。如果没有该请求头,说明网关的令牌转发配置有误。

  • 排查安全过滤器顺序
    确保oauth2ResourceServer的过滤器优先级高于匿名认证过滤器,避免匿名认证先触发。可通过显式指定过滤器顺序或排查自定义过滤器是否干扰认证流程。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 14:05:10