我可以通过 Keycloak 向有效负载令牌中的资源添加一些信息吗?

Can I add some information to resource in payload token by Keycloak?

我可以通过 Keycloak 向负载令牌中的资源添加一些信息吗? 我使用 keycloak 获取 jwt。令牌已分配给某些资源的角色,f.e。

"resource_access": {
    "subject-service": {
      "roles": [
        "ADMIN"
      ]
    },
    "account-service": {
      "roles": [
        "USER",
        
      ]
    }
  }

但我想为资源添加一些属性并在后端或前端使用它。 我想根据令牌中的数据分配权限 f.e.:

   "resource_access": {
        "subject-service": {
          "roles": [
            "ADMIN"
          ],
          "attribute1":[read,write,delete],
          "attribute2":[read],
          "attribute3":[write]
    
        },
        "account-service": {
          "roles": [
            "USER",
            
          ],
          "attribut1":[write],
        }
      } 

我可以通过 Keycloak 完成吗?

如果不自定义 Mapper,您将无法实现格式。 但是,开箱即用,您可以添加 Keycloak 自定义映射器。为此,请访问:

  • Select 你的 realm;
  • 转到clients
  • Select 您要针对其请求令牌的 client
  • 转到Mappers
  • 点击创建
  • Mapper typeselectHardcoded claim;
  • 相应地填写其余部分。

例如:

      "attribute1":[read,write,delete],
      "attribute2":[read],
      "attribute3":[write]

将是:

  • Token Claim Name:资源 1
  • Claim value : "{attribute1:[read,write,delete], attribute2:[read], attribute3:[write]}"
  • Claim JSON Type : JSON

以及令牌:

{
  (..)
  "realm_access": {
    "roles": [
      (..)
    ]
  },
  "resource_access": {
    "account-service": {
      "roles": [
       (..)
      ]
    },
    "account": {
      "roles": [
        (...)
      ]
    }
  },
  (...)
    "Resource1": "{
          attribute1:[read,write,delete], 
          attribute2:[read], 
          attribute3:[write]
     }"
}