Keycloak Java admin client authentication error after restart

Hello team,

I would like to ask your help in the following topic:

I have a Java application set up, where I use the keycloak provided keycloak-admin-client, I set up a Bean at the start of my application. I use it to ask Keycloak about users, groups, everything what is admin related.

@Bean
public Keycloak keycloak() {
    return KeycloakBuilder.builder() //
            .serverUrl(KEYCLOAK_SERVER_URL) //
            .realm(KEYCLOAK_REALM)//
            .username(KEYCLOAK_ADMIN_USERNAME) //
            .password(KEYCLOAK_ADMIN_PASSWORD) //
            .clientId(KEYCLOAK_ADMIN_CLIENT_ID) //
            .resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).build()) //
            .build();
}

It is working perfectly, but as soon as the keycloak server restarts (sadly it happens every day, since we are deploying to heroku), the first request to Keycloak will return with 401, the second call will be already alright.

My questions would be the following:

  • is it the right way to use the Keycloak admin client? Or should i set up an instance per request?
  • is there a possible configuration so after the keycloak server restarts, i could acquire a new authentication token?

Thank you in advance!