如何在 Spring 中解析 JWT 令牌中的值并分配给变量?

问题描述 投票:0回答:1

所以我目前正在获取我的 JWT 令牌并控制台记录它的值,如下所示:

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

if (authToken != null) {
    log.warn("Principal authorities:");
    authToken.getAuthorities().forEach(auth -> log.warn("authorities: [{}]", auth.getAuthority()));

Map<String, Object> attributes = Collections.emptyMap();
attributes = authToken.getTokenAttributes();
log.warn("Token attributes:");
attributes
    .entrySet()
    .forEach(attr -> log.warn("attributes: [{}:{}", attr.getKey(), attr.getValue()));

我的 JWT 的部分内容如下:

{
 "exp": 17283445,
 "iat": 17283445,
 .....
 "realm_access": {
  "roles": [
   "app-user"
  ]
 }
}

如果我想提取角色“app-user”中的值并将其分配给变量,我将如何提取它?

我有控制台记录了我的 JWT 属性,但没有记录如何提取单个值。

java spring jwt spring-security-oauth2
1个回答
0
投票

您可以在将 org.json 依赖项添加到您的项目后尝试此操作:

private void getUserRoles(String jsonStr) {
  JSONObject json = new JSONObject(jsonStr);
  JSONArray arrayOfTests = (JSONArray) ((JSONObject) json.get("realm_access")).get("roles");
  for (int i = 0; i < arrayOfTests.length(); i++) {
    System.out.println(arrayOfTests.get(i));
  }
}

在你的方法中:

getUserRoles(authToken);
© www.soinside.com 2019 - 2024. All rights reserved.