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

在Spring中解析JWT令牌角色值并赋值给变量的方法

提取JWT中realm_access的roles值

你可以通过逐层解析JWT属性的嵌套结构来提取目标角色值,具体实现如下:

实现步骤

  • 从JwtAuthenticationToken获取令牌属性映射attributes
  • 从映射中取出realm_access对应的嵌套对象(类型为Map)
  • 从realm_access中取出roles对应的列表(类型为List)
  • 从列表中提取目标角色值(比如第一个元素app-user)

代码示例

JwtAuthenticationToken authToken = (JwtAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

if (authToken != null) {
    Map<String, Object> attributes = authToken.getTokenAttributes();
    
    // 解析realm_access对象
    Map<String, Object> realmAccess = (Map<String, Object>) attributes.get("realm_access");
    if (realmAccess != null) {
        // 获取roles列表
        List<String> roles = (List<String>) realmAccess.get("roles");
        if (roles != null && !roles.isEmpty()) {
            // 提取第一个角色(这里是app-user)
            String targetRole = roles.get(0);
            // 赋值给变量后可按需使用
            log.warn("提取到的角色: [{}]", targetRole);
        }
    }
}

注意事项

  • 必须做好空值判断,避免NullPointerException,比如realm_access可能不存在、roles可能为空列表
  • 如果需要处理多个角色,可以遍历roles列表逐一操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 00:38:13