2

I want to store information (like an external ID) in custom user attributes after registration. The end goal is to have this information in the JWT token.

I'm having trouble finding the right way to do it. I think this may not be a good design.

More details on my use case: When a user registers on keycloak, I have to create the user on an external application and I want to save this external ID on keycloaK.

I was thinking Event Listener SPI and do some stuff after registration, but it feel like overkill

dreamcrash
  • 47,137
  • 25
  • 94
  • 117

1 Answers1

3

I want to store information (like an external ID) in custom user attributes after registration. The end goal is to have this information in the JWT token.

After the user registration you need to:

  1. add the external ID as a user custom attribute
  2. create a Mapper to map that attribute to a claim on the JWT token

For 1. (setting the user attributes) you can use the endpoint:

PUT <YOUR_KEYCLOAK_DOMAIN>/auth/admin/realms/<YOUR_REALM>/users/<USER_ID>

with the payload '{"attributes":{"ExternalID":["<THE_EXTERNAL_ID>"]}}'

the user ID you can get it from:

GET <YOUR_KEYCLOAK_DOMAIN>/auth/admin/realms/<YOUR_REALM>/users/?username=<THE_USERNAME>

For a more detailed answer on how to set user attributes (including for the old and new Keycloak APIs) please have a look at the this SO answer.

For 2. (creating the Mapper):

you can also use the Keycloak Admin rest API. For a more detailed answer on how to create Protocol Mappers for user-attributes (including for the old and new Keycloak APIs) please have a look at the this SO answer.

or you can do it via Keycloak Admin UI as follows, in the Keycloak 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
  • Select Mapper Type as User Attribute
  • Fill up the field User Attribute as ExternalID
  • Fill up the remaining 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 User Attribute
  • Fill up the field User Attribute as ExternalID
  • Fill up the remaining fields, accordingly
  • Click on Save

The label ExternalID can be replaced with what you will be using.

This is enough to have the External ID being injected into the JWT tokens.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117