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

Viewed 815

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.

1 Answers

Instead of an user attribute, use a Client Mapper Instead. 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;
  • Token Claim Name : realm name
  • Claim value : the name of the realm.
  • Fill up the rest accordingly.

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

Related