Keycloak Impersonation with Spring Boot

Hello everyone

The goal of my spring boot application is it to impersonate a user and then be logged in as that user.
I am trying to realise this function by implementing the impersonation function from Keycloak, but unfortunately I am having some difficulties.

So far I have been able to impersonate a user with the help of the rest API I managed to perform an impersonation with the token-exchange.
This function returns an access-token to me. My problem is that I cant figure out, how to switch out the token of the current logged in user with the impersonated users token in my spring boot application.
I have tried to overwrite the keycloaksecuritycontext, but to do that I also need the id-token. When I try to get an id-token with the help of the token-exchange I get the error, that the “grant-type id-token isnt supported”.

I am just wondering if the impersonation process has been completly implemented, so that it can be used outside of the keycloak admin console.
So far I havent been able to find any examples online, on how to exchange the current logged in user with the impersonated user.

If someone has information that could help me solve this problem I would appreciate it. Below I have listed some technical details.

Technical details:

  • Spring Boot: version 2.4.5
  • Keycloak admin client: version12.0.2
  • Keycloak server: version 12.0.2

Kind regards