Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to enrich Keycloak token via external service

Tags:

java

keycloak

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?

like image 939
Hans Sperker Avatar asked Jan 09 '19 16:01

Hans Sperker


People also ask

How do I get JWT token from Keycloak?

GET AccessTokenWe send a POST request to the token endpoint: http://localhost:8090/auth/realms/wstutorial/protocol/openid-connect/token. We use openid-connect protocol which is an authentication layer on top of OAuth 2.0. Within the POST request we send data as name=value pairs separated with &

How do you get a Keycloak token?

Navigate to the Postman Authorization tab of your request. From the Type dropdown menu, select OAuth 2.0: Click on the Get New Access Token button that will open a dialog box for configuring the identity server (Keycloak in our case).


1 Answers

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.

like image 115
cdan Avatar answered Sep 19 '22 11:09

cdan