首页 > 解决方案 > 令牌中的 KeyCloak 组 ID 丢失

问题描述

我目前正在设置一个新的 KeyCloak 实例,我正在尝试实现以下目标:用户将被放置在 - 组 - 这些组将获得客户特定的角色

例如,我有“发布者”角色和几组发布者:Publisher1、Publisher2、...

因此,当用户登录时,我可以确定他是否是发布者,然后让他访问网站上的一组特定功能。然后,小组将缩小他将收到的所有信息的范围。

就像该角色将授予他对 REST API 的访问权限一样,该组将过滤他将收到的结果。

在 SQL 中:SELECT * FROM xyz where publisher_id = ?

在令牌中,我想查看这些信息。使用评估功能时,我目前收到以下信息:

{
  "jti": "3e96fc9d-b1dc-428a-8f8e-0661f9cf265b",
  "exp": 1578303161,
  "nbf": 0,
  "iat": 1578302861,
  "iss": "https://prodo-sso-ti.ariva-services.de/auth/realms/PRODO",
  "aud": "account",
  "sub": "55bed571-dd3b-4282-8688-5da543517a49",
  "typ": "Bearer",
  "azp": "dashboard",
  "auth_time": 0,
  "session_state": "12ab2b8c-dc9a-42ca-b106-1a213dd38fc0",
  "acr": "1",
  "allowed-origins": [
    "https://secretlink"
  ],
  "realm_access": {
    "roles": [
      "offline_access",
      "uma_authorization"
    ]
  },
  "resource_access": {
    "account": {
      "roles": [
        "manage-account",
        "manage-account-links",
        "view-profile"
      ]
    },
    "dashboard": {
      "roles": [
        "Publisher"
      ]
    }
  },
  "scope": "openid profile email",
  "group_membership": [
    "/Publisher1"
  ],
  "email_verified": true,
  "name": "My Name",
  "preferred_username": "mb",
  "locale": "de",
  "given_name": "My",
  "family_name": "Name",
  "email": "my@name.de"
}

我激活了组成员映射器来获取用户所在的组。问题是,我只得到组的名称,而我需要更有用的东西,比如 ID。因此,我尝试将属性添加到具有数值“1”的组“publisher_id”。

如何在组成员信息或其他地方也获得此 publisher_id。或者也许我走错了路,这可能会以某种不同的方式实现?

我很感激任何提示:)

标签: keycloak

解决方案


有一种简单的方法可以将 Groups Id 添加到令牌:

  1. 为您的客户创建一个新的客户范围

客户范围 -> 创建 -> 客户范围模板(受众模板) -> your_client_name

  1. 在新的客户端范围中创建一个新的映射器

客户范围 -> your_client_name -> 映射器 -> 创建

  1. 设置一些名称,Mapper Type必须是Script Mapper

然后将此代码粘贴到脚本部分:

/**
 * Available variables: 
 * user - the current user
 * realm - the current realm
 * token - the current token
 * userSession - the current userSession
 * keycloakSession - the current userSession
 */


//insert your code here...
var groups = [];
for each (var group in user.getGroups()) groups.push(group.getId());
token.setOtherClaims("groups_ids", 
    Java.to(groups, "java.lang.String[]")
);

不要忘记设置Add to access token

您将在您的令牌中看到它: groups_ids


推荐阅读