1

I need to get access/refresh pair (or at least access) tokens from a custom REST endpoint.

So in general I need programmatically create a user session from SPI by user ID(without a user password)

Could you please suggest a better way or any examples, I'm not experienced in keycloak and I feel like missing something.

my keycloak version: 15.0.2

I think about using token_exchange and: http://{ip}:{port}/auth/realms/{realm}/protocol/openid-connect/token

But not sure if it's will work as I expect, and if it's the best way.

dreamcrash
  • 47,137
  • 25
  • 94
  • 117
M.Surnyk
  • 33
  • 4

1 Answers1

0

If I understood correclty, you want to do user impersonation. Ie: create a token on behalf of user, without his consent.

To do that, externally to Keyckoak, you can use token exchange feature. This doc will help you: https://www.keycloak.org/docs/latest/securing_apps/#_token-exchange

Basically, the idea is that you'll give to a client permission to create tokens for any user you want.

But your question is how to do that from inside a Service Provider Interface loaded by Keycloak.

To programmatically impersonate a user, you can actually just do as the token exchange code do.

Take a look at https://github.com/keycloak/keycloak/blob/a912558d29c685ef912baa04b8cc823a70c6fd2d/services/src/main/java/org/keycloak/protocol/oidc/DefaultTokenExchangeProvider.java#L131

You'll have to create a session for the desired user and build her token.

The crux it's here https://github.com/keycloak/keycloak/blob/a912558d29c685ef912baa04b8cc823a70c6fd2d/services/src/main/java/org/keycloak/protocol/oidc/DefaultTokenExchangeProvider.java#L227

motobói
  • 1,687
  • 18
  • 24
  • Thank you @motobói. Yes, that's my current plan, but I'm unsure if it's the best solution to my problem. Do you know if possible to execute the **token-exchange** flow, avoiding the rest endpoint but by some service method from keycloak SPI code? – M.Surnyk Jan 31 '23 at 08:57
  • Now I see that I misunderstood your question. To programmatically impersonate a user, you actually just do as the token exchange do. Take a look at https://github.com/keycloak/keycloak/blob/a912558d29c685ef912baa04b8cc823a70c6fd2d/services/src/main/java/org/keycloak/protocol/oidc/DefaultTokenExchangeProvider.java#L131 you'll have to create a session for the desired user and build her token. The crux it's here https://github.com/keycloak/keycloak/blob/a912558d29c685ef912baa04b8cc823a70c6fd2d/services/src/main/java/org/keycloak/protocol/oidc/DefaultTokenExchangeProvider.java#L227 – motobói Feb 01 '23 at 03:39