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

如何在Spring Security资源服务器(WebFlux)中设置当前登录用户信息

Spring WebFlux资源服务器中通过客户端凭证流Token获取用户信息的问题解决

1. 替换SecurityContextHolder为ReactiveSecurityContextHolder

WebFlux基于异步非阻塞的反应式架构,传统的SecurityContextHolder是线程绑定的,无法适配这种场景。必须使用ReactiveSecurityContextHolder来获取安全上下文:

// 测试用例中可使用block()同步获取,实际业务中建议整合到反应式流里
ReactiveSecurityContextHolder.getContext()
    .map(SecurityContext::getAuthentication)
    .map(auth -> {
        LOG.info("当前登录主体: {}", auth.getPrincipal());
        return auth;
    })
    .block();

2. 明确客户端凭证流的默认行为

客户端凭证流是客户端身份认证,而非用户认证。默认情况下,资源服务器解析JWT后生成的是ClientAuthenticationToken,其principal字段存储的是客户端ID。如果你的JWT中包含用户相关的Claims(比如sub字段),需要自定义转换器来提取用户信息。

3. 自定义JWT到Authentication的转换

如果需要像之前那样生成UsernamePasswordAuthenticationToken,可以配置自定义的JwtAuthenticationConverter:

@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
    return new JwtAuthenticationConverter() {
        @Override
        protected Authentication extractAuthentication(Jwt jwt) {
            // 从JWT中提取用户名,比如取sub字段
            String username = jwt.getSubject();
            // 根据实际JWT结构提取权限列表
            List<GrantedAuthority> authorities = Collections.emptyList();
            return new UsernamePasswordAuthenticationToken(username, null, authorities);
        }
    };
}

然后在YAML配置中关联这个转换器:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://localhost:9000
          jwt-authentication-converter-ref: jwtAuthenticationConverter

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 06:10:41