5
votes

What is the proper way of extending Keycloak -- for example via Service Provider Interface (SPI) -- to enrich the issued JWT token with information fetched from another service but without delegating the user credential check to the other service?

1

1 Answers

5
votes

You create - what Keycloak documentation refers to as - a Protocol Mapper. They are various types of them that you can find out by going to the Clients > your_client > Mappers menu and try to create one. Besides, you should see that you can choose which JWT token you want to enrich, ID token or Access token. In your case, you need to customise the mapper's logic enough to fetch info from another service. There are two types of mapper that allow that (at least as far as I know):

  1. The Script mapper: allows you to code a custom mapper in JavaScript, so you can implement the service call and add the result to the token claims in javascript. See the example on Stackoverflow, and source code of the mapper for more info. This has some limitations, e.g. does not support multi-valued claims properly.

  2. Implement the mapper directly in Java: full flexibiliy but more work (implement Java interface AbstractOIDCProtocolMapper). See this Custom Keycloak Protocol Mapper for group membership for instance.