How to obtain an access token within a Keycloak SPI?

Viewed 1253

Use case:
From inside a EventListenerProvider on an event I want to make an authenticated REST call to one of our keycloak secured service. For this I need a token.

First I just test printing the token to check whether it is succeeded.

  public void onEvent(final Event event) {
        Keycloak k = Keycloak.getInstance("http://localhost:8080/auth", "myrealm", "myemail@gmail.com", "password", "myclient");
        AccessTokenResponse t = k.tokenManager().getAccessToken();
        logger.info(t.getSessionState());
        logger.info(t.getToken());
   }

Unfortunatly both the session_state and token is NULL.

All the data are correct, the url,the realm..etc. Otherwise we would know about that. Keycloak doesnt log anything just silently returns null.
On the top of that I can use the above code from anywhere else and it works! I can use it from a plain java main() method and still works. Getting token by hand via postman also works.

What is wrong with the Keycloak Provider? How can I get an accesstoken for a particular user?

1 Answers

You can use the following example to create a AccessToken:

public String getAccessToken(UserModel userModel, KeycloakSession keycloakSession) {
    KeycloakContext keycloakContext = keycloakSession.getContext();

    AccessToken token = new AccessToken();
    token.subject(userModel.getId());
    token.issuer(Urls.realmIssuer(keycloakContext.getUri().getBaseUri(), keycloakContext.getRealm().getName()));
    token.issuedNow();
    token.expiration((int) (token.getIat() + 60L)); //Lifetime of 60 seconds

    KeyWrapper key = keycloakSession.keys().getActiveKey(keycloakContext.getRealm(), KeyUse.SIG, "RS256");

    return new JWSBuilder().kid(key.getKid()).type("JWT").jsonContent(token).sign(new AsymmetricSignatureSignerContext(key));
  }

Note that you also need to specify <module name="org.keycloak.keycloak-services"/> in your jboss-deployment-structure.

Related