How to store external data in keycloak user model after registration

Viewed 1013

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

1 Answers

After the user registration you can add the external ID as a user custom attribute using the endpoint:

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

with the payload {"id":"<USER_ID>","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>

I have created scripts to this in my repo. The scripts also make sure that the new attributes are added to the old ones, instead of replacing them.

For both of this endpoints you need to send in the headers the token from a user-alike admin.

In the Keycloak go to:

  • Your Realm
  • Clients > client that you will be using to authenticate your app against,
  • Mappers
  • Create
  • Select Mapper Type : User Attribute
  • User Attribute : ExternalID
  • Fill up the rest.

The label ExternalID you can replace it with what you will be using.

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

Related