authorizationkeycloakidpkeycloak-spi

How to programmatically create keycloak user session from SPI?


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.


Solution

  • 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