Search code examples
javakeycloak

keycloak offline token with Java


I am using authentication of users in Java 8 against Keycloak, with the Keycloak adapter API for Java.

In this case, the class KeycloakBuilder (keycloak-admin-client-6.0.0.jar) builds a Keycloak instance to perform authentication operations.

how can I request an offline token rather than a normal Bearer token using this API?

Have not found parameter or way to request it. I need tokens with 1 month expiration time, which cannot get unless change the "SSO Session Max" field, but I don´t want this to affect other Clients or users in the same Realm / client.


Solution

  • I post a possible solution using keycloak-authz-client library instead.

    As stated by @Philipp , it is also necessary that the user you log in with has the role offline_access.

    public String login(String username, String password) {
        String authServerUrl = "http://localhost:18080/auth"; // Your keycloak auth endpoint
        String realm = "realm"; // Realm
        String clientId = "client"; // Client
        Map<String, Object> clientCredentials = new LinkedHashMap<String, Object>();
        clientCredentials.put("secret", "clientSecret"); // Client secret (Access Type: Confidential)
        
        Configuration configuration = new Configuration(
            authServerUrl,
            realm,
            clientId,
            clientCredentials,
            null
        );
        
        AuthzClient authzClient = AuthzClient.create(configuration);
        
        AuthorizationRequest request = new AuthorizationRequest();
        request.setScope("offline_access");
        
        AuthorizationResponse response = authzClient.authorization(username, password).authorize(request);
        
        return response.getRefreshToken(); // response.getToken() returns the bearer token
    }