package org.gcube.common.keycloak; import org.gcube.common.keycloak.model.AccessToken; import org.gcube.common.keycloak.model.RefreshToken; import org.gcube.common.keycloak.model.TokenResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class KeycloakClientHelper { protected static Logger logger = LoggerFactory.getLogger(KeycloakClientHelper.class); /** * The public GW used to obtain the token, is not declared final since it can be changed if necessary at runtime */ private static String GATEWAY_CLIENT_ID = "d4science-internal-gateway"; /** * Sets the new default GW clientId used for all the queries to the Keycloak server. * Note: The operation will logged as WARN to be visible. * @param gatewayClientId the new GW clientId */ public static void setDefaultGWClientID(String gatewayClientId) { logger.warn("The default GW clientId will be changed to: {}", gatewayClientId); GATEWAY_CLIENT_ID = gatewayClientId; } /** * Gets a new {@link TokenResponse}, containing the {@link AccessToken} and the {@link RefreshToken} from the Keycloak server in the environment of the context represented by the context parameter. * The context parameter is also used as audience for the token. * * @param context the context ot be used for discovery and for audience * @param username the user's username * @param password the user's password * @return the token response from the Keycloak server * @throws KeycloakClientException if an error occurs during the process */ public static TokenResponse getTokenForUser(String context, String username, String password) throws KeycloakClientException { logger.debug("Getting new token for user '{}' in context '{}'", username, context); logger.trace("Getting OIDC token for user '{}' using configured default GW clientId '{}'", username, GATEWAY_CLIENT_ID); TokenResponse oidcTR = KeycloakClientFactory.newInstance().queryOIDCTokenOfUser(context, GATEWAY_CLIENT_ID, "", username, password); logger.trace("Getting UMA token in the '{}' context", context); return KeycloakClientFactory.newInstance().queryUMAToken(context, oidcTR, context, null); } }