Search code examples
jwtkeycloakaccess-token

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


Can I add some information to resource in payload token by Keycloak? I use keycloak for taking jwt. Token have roles assigned to some resource, f.e.

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

But I would like to add some attributes to resource and used it on backend or frontend. I would like to assign permissions based on the data in the token f.e.:

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

Can I do it by Keycloak?


Solution

  • Without doing your custom Mapper, you will not be able to achieve the format. However, out of the box you add Keycloak custom Mappers. For that go to:

    • Select your realm;
    • Go to clients;
    • Select the client that you are going to request the token against;
    • Go to Mappers;
    • Click Create
    • In Mapper type select Hardcoded claim;
    • Fill up the rest accordingly.

    For instance for:

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

    would be:

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

    And the token:

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