Package org.gcube.common.iam
Class D4ScienceIAMClient
java.lang.Object
org.gcube.common.iam.D4ScienceIAMClient
Helper class that acts as IAM client providing authentication and authorization using the IAM hiding the underlying implementation
- Author:
- Mauro Mugnaini (Nubisware S.r.l.)
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic longAn unknownkidmakes the key set be fetched again only if the cached one is older than this (milliseconds).protected static org.slf4j.LoggerLogger instance for this classstatic longHow long the realm public key is kept before asking the IAM again (milliseconds, 0 disables the cache).static longA key that failed a verification is fetched again only if the cached one is older than this (milliseconds).static final Stringstatic booleanFlag to enable/disable dynamic scopes functionality -
Method Summary
Modifier and TypeMethodDescriptionstatic StringasD4sContextDynamicScope(String context) authenticate(String clientId, String clientSecret) Authenticates the client with provided id and secretauthenticate(String clientId, String clientSecret, String context) Authenticates the client with provided credentials, reducing the token audience to the requested `context`authenticateUser(String username, String password) Deprecated.this authn method is deprecated in the oauth2 specifications (see https://oauth.net/2/grant-types/password/)authenticateUser(String username, String password, String context) Deprecated.this authn method is deprecated in the oauth2 specifications (see https://oauth.net/2/grant-types/password/)authenticateUser(String clientId, String clientSecret, String username, String password) Deprecated.this authn method is deprecated in the oauth2 specifications (see https://oauth.net/2/grant-types/password/)authenticateUser(String clientId, String clientSecret, String username, String password, String context) Deprecated.this authn method is deprecated in the oauth2 specifications (see https://oauth.net/2/grant-types/password/)authenticateWithCode(String clientId, String clientSecret, String code, String redirectUri, String codeVerifier) Authenticates with the code received on the redirect URI of the authorization code flow.authorizationURL(String clientId, String redirectUri) Starts the URL of the authorization endpoint the browser has to be redirected to (authorization code flow).Directly authorizes the client by using the provided credentials, for the specific context audience and with no optional permissionsDirectly authorizes the client by using the provided credentials, for the specific context audience and with optional permissionsstatic voidEmpties the realm public keys cache (e.g. after a known key rotation).static longexpiryMillis(String token) fromTokens(String accessToken, String refreshToken, String idToken) Wraps tokens this component obtained elsewhere (e.g. by a login performed by another component) into theIAMResponseAPI: claims, expiry, refresh, exchange, verification and logout, with no request performed.protected org.gcube.common.keycloak.KeycloakClientReturns the underlying Keycloak client instance.Returns the base URL of the realm.introspect(String token) Introspects a token with the credentials set bywithIntrospectionCredentials(String, String).introspect(String token, String clientId, String clientSecret) Asks the IAM server of this client (never the issuer named in the token) whether the token is active and which claims it carries (token introspection, RFC 7662).booleanisTokenValid(String token) Checks if the token is valid (signature and expiration).booleanisTokenValid(String token, boolean checkExpiration) Checks if the token is valid and optionally checks for expiration.static D4ScienceIAMClientnewInstance(String contextInfra) Creates a new client for the specific context, in the default IAM realm.static D4ScienceIAMClientnewInstance(String contextInfra, String realm) Creates a new client for the specific context, in the default realm.static D4ScienceIAMClientnewInstance(URL realmBaseURL) Creates a new client with the provided base URL.static D4ScienceIAMClientnewInstanceForTokenEndpoint(URL tokenEndpoint) Creates a new client from the full token endpoint URL of the realm (...static org.gcube.common.keycloak.model.AccessTokenparseAccessToken(String token) Reads the claims of a token JWT string WITHOUT verifying signature nor expiry (useverifyToken(String)for that).static voidsetDefaultGatewayClientID(String gatewayClientId) Sets the new default GWclientIdused for all the queries to the IAM server.voidverifyToken(String token) Verifies the token signature and also checks the expiration.voidverifyToken(String token, boolean checkExpiration) Verifies the token signature and optionally checks for expiration.withIntrospectionCredentials(String clientId, String clientSecret) Sets the service credentials used byintrospect(String).
-
Field Details
-
logger
protected static org.slf4j.Logger loggerLogger instance for this class -
USE_DYNAMIC_SCOPES
public static boolean USE_DYNAMIC_SCOPESFlag to enable/disable dynamic scopes functionality -
ROOT_DYNAMIC_SCOPE_FOR_ENABLING
- See Also:
-
PUBLIC_KEY_CACHE_TTL_MILLIS
public static volatile long PUBLIC_KEY_CACHE_TTL_MILLISHow long the realm public key is kept before asking the IAM again (milliseconds, 0 disables the cache). -
PUBLIC_KEY_MIN_REFRESH_MILLIS
public static volatile long PUBLIC_KEY_MIN_REFRESH_MILLISA key that failed a verification is fetched again only if the cached one is older than this (milliseconds). -
JWKS_UNKNOWN_KID_REFRESH_MILLIS
public static volatile long JWKS_UNKNOWN_KID_REFRESH_MILLISAn unknownkidmakes the key set be fetched again only if the cached one is older than this (milliseconds).
-
-
Method Details
-
setDefaultGatewayClientID
Sets the new default GWclientIdused for all the queries to the IAM server. Note: The operation will logged as WARN to be visible.- Parameters:
gatewayClientId- the new GWclientId
-
newInstance
public static D4ScienceIAMClient newInstance(String contextInfra) throws D4ScienceIAMClientException Creates a new client for the specific context, in the default IAM realm.- Parameters:
contextInfra- the context to be used to obtain the base URL of the infrastructure- Returns:
- the client to be used for authn and authz requests
- Throws:
D4ScienceIAMClientException- if an error occurs obtaining the base URL
-
newInstance
public static D4ScienceIAMClient newInstance(String contextInfra, String realm) throws D4ScienceIAMClientException Creates a new client for the specific context, in the default realm.- Parameters:
contextInfra- the context to be used to obtain the base URL of the infrastructurerealm- the IAM realm- Returns:
- the client to be used for authn and authz requests
- Throws:
D4ScienceIAMClientException- if an error occurs obtaining the base URL
-
newInstance
Creates a new client with the provided base URL.- Parameters:
realmBaseURL- the realm base URL- Returns:
- the client to be used for authn and authz requests
-
newInstanceForTokenEndpoint
Creates a new client from the full token endpoint URL of the realm (.../realms/<realm>/protocol/openid-connect/token), as found in configurations.- Parameters:
tokenEndpoint- the token endpoint URL- Returns:
- the client to be used for authn and authz requests
- Throws:
IllegalArgumentException- if the URL is not a token endpoint
-
getKeycloakClient
protected org.gcube.common.keycloak.KeycloakClient getKeycloakClient()Returns the underlying Keycloak client instance.- Returns:
- the Keycloak client
-
getRealmBaseURL
Returns the base URL of the realm.- Returns:
- the realm base URL
-
authenticate
public D4ScienceIAMClientAuthn authenticate(String clientId, String clientSecret) throws D4ScienceIAMClientException Authenticates the client with provided id and secret- Parameters:
clientId- the client idclientSecret- the client secret- Returns:
- the authn object
- Throws:
D4ScienceIAMClientException- if an error occurs during authn process
-
authenticate
public D4ScienceIAMClientAuthn authenticate(String clientId, String clientSecret, String context) throws D4ScienceIAMClientException Authenticates the client with provided credentials, reducing the token audience to the requested `context`- Parameters:
clientId- the client idclientSecret- the client secretcontext- the requested token context audience (e.g. a specific context or another client)- Returns:
- the authn object
- Throws:
D4ScienceIAMClientException- if an error occurs during authn process
-
authenticateUser
public D4ScienceIAMClientAuthn authenticateUser(String username, String password) throws D4ScienceIAMClientException Deprecated.this authn method is deprecated in the oauth2 specifications (see https://oauth.net/2/grant-types/password/)Authenticates the user with provided username and password by using the defaultclientId.- Parameters:
username- the user's usernamepassword- the user's password- Returns:
- the authn object
- Throws:
D4ScienceIAMClientException- if an error occurs during authn process
-
authenticateUser
public D4ScienceIAMClientAuthn authenticateUser(String username, String password, String context) throws D4ScienceIAMClientException Deprecated.this authn method is deprecated in the oauth2 specifications (see https://oauth.net/2/grant-types/password/)Authenticates the user with provided username and password by using the defaultclientId.- Parameters:
username- the user's usernamepassword- the user's passwordcontext- the requested token context audience (e.g. a specific context or another client)- Returns:
- the authn object
- Throws:
D4ScienceIAMClientException- if an error occurs during authn process
-
authenticateUser
public D4ScienceIAMClientAuthn authenticateUser(String clientId, String clientSecret, String username, String password) throws D4ScienceIAMClientException Deprecated.this authn method is deprecated in the oauth2 specifications (see https://oauth.net/2/grant-types/password/)Authenticates the user with provided username and password- Parameters:
clientId- the client idclientSecret- the client secretusername- the user's usernamepassword- the user's password- Returns:
- the authn object
- Throws:
D4ScienceIAMClientException- if an error occurs during authn process
-
authenticateUser
public D4ScienceIAMClientAuthn authenticateUser(String clientId, String clientSecret, String username, String password, String context) throws D4ScienceIAMClientException Deprecated.this authn method is deprecated in the oauth2 specifications (see https://oauth.net/2/grant-types/password/)Authenticates the user with provided credentials, reducing the token audience to the requested `context`.- Parameters:
clientId- the client idclientSecret- the client secretusername- the user's usernamepassword- the user's passwordcontext- the requested token context audience (e.g. a specific context or another client)- Returns:
- the authn object
- Throws:
D4ScienceIAMClientException- if an error occurs during authn process
-
authorize
public D4ScienceIAMClientAuthz authorize(String clientId, String clientSecret, String context) throws D4ScienceIAMClientException Directly authorizes the client by using the provided credentials, for the specific context audience and with no optional permissions- Parameters:
clientId- the client idclientSecret- the client secretcontext- the requested token context audience (e.g. a specific context or another client)- Returns:
- the authz object
- Throws:
D4ScienceIAMClientException- if an error occurs during authz process
-
authorize
public D4ScienceIAMClientAuthz authorize(String clientId, String clientSecret, String context, List<String> permissions) throws D4ScienceIAMClientException Directly authorizes the client by using the provided credentials, for the specific context audience and with optional permissions- Parameters:
clientId- the client idclientSecret- the client secretcontext- the requested token context audience (e.g. a specific context or another client)permissions- the optional permissions- Returns:
- the authz object
- Throws:
D4ScienceIAMClientException- if an error occurs during authz process
-
verifyToken
public void verifyToken(String token) throws org.gcube.io.jsonwebtoken.security.SignatureException, org.gcube.io.jsonwebtoken.ExpiredJwtException, org.gcube.io.jsonwebtoken.JwtException, Exception Verifies the token signature and also checks the expiration.- Parameters:
token- the base64 JWT token string- Throws:
org.gcube.io.jsonwebtoken.security.SignatureException- if the token signature is invalidorg.gcube.io.jsonwebtoken.ExpiredJwtException- if the token is expiredorg.gcube.io.jsonwebtoken.JwtException- if another JWT related problem is foundException- if an unexpected error occurs (e.g. constructing the verifier)
-
withIntrospectionCredentials
Sets the service credentials used byintrospect(String).- Parameters:
clientId- the client id of the calling serviceclientSecret- the client secret of the calling service- Returns:
- this client
-
introspect
Introspects a token with the credentials set bywithIntrospectionCredentials(String, String).- Parameters:
token- the token to introspect- Returns:
- the typed result
- Throws:
D4ScienceIAMClientException- if no credentials are set or the call to the IAM server fails
-
introspect
public IntrospectionResult introspect(String token, String clientId, String clientSecret) throws D4ScienceIAMClientException Asks the IAM server of this client (never the issuer named in the token) whether the token is active and which claims it carries (token introspection, RFC 7662). The IAM server decides which issuers it accepts (federation): the caller only deserializes the answer. Connect and read timeouts are those of the underlying client (gcube.keycloak.connectTimeout/gcube.keycloak.readTimeout, 10 s by default).- Parameters:
token- the token to introspectclientId- the client id of the calling serviceclientSecret- the client secret of the calling service- Returns:
- the typed result; an inactive token gives
IntrospectionResult.isActive()false - Throws:
D4ScienceIAMClientException- if the credentials or the token are missing or the call to the IAM server fails
-
verifyToken
public void verifyToken(String token, boolean checkExpiration) throws org.gcube.io.jsonwebtoken.security.SignatureException, org.gcube.io.jsonwebtoken.ExpiredJwtException, org.gcube.io.jsonwebtoken.JwtException, Exception Verifies the token signature and optionally checks for expiration.- Parameters:
token- the base64 JWT token stringcheckExpiration- flag to enable/disable expiration check- Throws:
org.gcube.io.jsonwebtoken.security.SignatureException- if the token signature is invalidorg.gcube.io.jsonwebtoken.ExpiredJwtException- if the token is expiredorg.gcube.io.jsonwebtoken.JwtException- if another JWT related problem is foundException- if an unexpected error occurs (e.g. constructing the verifier)
-
isTokenValid
Checks if the token is valid (signature and expiration).- Parameters:
token- the base64 JWT token string- Returns:
trueif the token is valid,falseotherwise- Throws:
D4ScienceIAMClientException- if an error occurs during the verification process
-
isTokenValid
public boolean isTokenValid(String token, boolean checkExpiration) throws D4ScienceIAMClientException Checks if the token is valid and optionally checks for expiration.- Parameters:
token- the base64 JWT token stringcheckExpiration-- Returns:
trueif the token is valid,falseotherwise- Throws:
D4ScienceIAMClientException- if an error occurs during the verification process
-
clearPublicKeyCache
public static void clearPublicKeyCache()Empties the realm public keys cache (e.g. after a known key rotation). -
fromTokens
Wraps tokens this component obtained elsewhere (e.g. by a login performed by another component) into theIAMResponseAPI: claims, expiry, refresh, exchange, verification and logout, with no request performed.- Parameters:
accessToken- the access token JWT (an empty or opaque token is accepted, its claims are then not readable)refreshToken- the refresh token JWT, can benullidToken- the ID token JWT, can benull- Returns:
- the authn object over the given tokens
-
authenticateWithCode
public D4ScienceIAMClientAuthn authenticateWithCode(String clientId, String clientSecret, String code, String redirectUri, String codeVerifier) throws D4ScienceIAMClientException Authenticates with the code received on the redirect URI of the authorization code flow.- Parameters:
clientId- the client id the code was issued toclientSecret- the client secret,nullor empty for a public clientcode- the authorization coderedirectUri- the redirect URI used in the authorization requestcodeVerifier- the PKCE code verifier,nullif PKCE was not used- Returns:
- the authn object
- Throws:
D4ScienceIAMClientException- if the exchange fails
-
authorizationURL
public AuthorizationURLBuilder authorizationURL(String clientId, String redirectUri) throws D4ScienceIAMClientException Starts the URL of the authorization endpoint the browser has to be redirected to (authorization code flow).- Parameters:
clientId- the client idredirectUri- the redirect URI the IAM will bring the code to- Returns:
- the builder to set scope, state, PKCE and other parameters
- Throws:
D4ScienceIAMClientException- if the endpoint URL cannot be constructed
-
parseAccessToken
public static org.gcube.common.keycloak.model.AccessToken parseAccessToken(String token) throws D4ScienceIAMClientException Reads the claims of a token JWT string WITHOUT verifying signature nor expiry (useverifyToken(String)for that).- Parameters:
token- the access (or ID) token JWT, with or without theBearerprefix- Returns:
- the token claims
- Throws:
D4ScienceIAMClientException- if the token cannot be read
-
expiryMillis
- Parameters:
token- a JWT string (access, refresh or ID token), signature NOT verified- Returns:
- the
expclaim in milliseconds since the epoch, or 0 if the token is null, unreadable or has noexp
-
asD4sContextDynamicScope
-