Search code examples
jwtkeycloakaccess-token

Keycloak client mapper to show the relam name as individual attibute in JWT token


By default keycloak (here version 11) provides information about the realm, a token was fetched for, only parsing the iss attribute of the token payload. e.g.

{
  "exp": ...,
  "iat": ...,
  "jti": "...",
  "iss": "http://localhost:8088/idp-provider-context/auth/realms/realmname",
  "aud": [...

Is there a build in way, like a client mapper, to add the information about the realm name directly as a dedicated attribute to the JWT-token?

One workaround would be to add an attribute "realmname" to each user and setting the realmname as the value. But on the one hand this seems to be a bit messy, as it is redundant information. On the other hand this could speed up the application a bit, as tokens/users without this attribute or the wrong value in it could be already count as invalid without requesting the backend. This would identify users not created in the desired process, defined for the application.


Solution

  • Instead of a user attribute, use a Client Mapper Instead. For that go to:

    • Select your realm
    • Go to clients
    • Select the appropriate client for your use-case

    (For the OLD Keycloak UI)

    • Go to Mappers
    • Click Create
    • In Mapper type select Hardcoded claim
    • Fill up the field Token Claim Name as realm name
    • Fill up the field Claim value as the name of the realm
    • Fill up the renaming fields, accordingly.
    • Click on Save

    (For the NEW Keycloak UI)

    • Go to the tab Client Scopes
    • Click on the scope -dedicated (e.g., test-dedicated in my example)

    enter image description here

    • Click on Configure a new mapper (or Add Mapper > By configuration if you have already created mappers before for this client)

    enter image description here

    • Select Hardcoded claim
    • Fill up the field Token Claim Name as realm name
    • Fill up the field Claim value as the name of the realm
    • Fill up the renaming fields, accordingly.
    • Click on Save

    The client will be the client that you are using to authenticate against.