Class OAuth2Client<T extends OAuth2ClientConfiguration>
- java.lang.Object
-
- org.forgerock.oauth.clients.oauth2.OAuth2Client<T>
-
- Type Parameters:
T- type of OAuth client configuration to be used.
- All Implemented Interfaces:
OAuthClient
- Direct Known Subclasses:
FacebookClient,LinkedInClient,OpenIDConnectClient
public class OAuth2Client<T extends OAuth2ClientConfiguration> extends Object implements OAuthClient
OAuth 2.0 Client Implementation that supports the Authorization Code Grant Flow.
-
-
Field Summary
Fields Modifier and Type Field Description static StringACCEPT_HEADERAccept header.static StringACCESS_TOKENThe access token issued by the authorization server.protected Function<JsonValue,JsonValue,OAuthException>addExpireTimeAdds the actual time the token expires.static StringAPPLICATION_JSONapplication/json.static StringAUTHORIZATION_CODEString used to verify the resource owner who granted the authorization at the authorization server.static StringAUTHORIZATION_HEADERAuthorization header.static StringBASIC_AUTHBasic Auth.static StringBEARER_TOKENToken Type.static StringCLIENT_IDClient Identifier.static StringCLIENT_SECRETClient Password.protected ClockclockClockused to handle token expire times.static StringCODEA type of response_type.static StringDATAURI safe data that MUST not be modified by the client and stored in theDataStore.static StringEXPIRE_TIMEExpire time.static StringEXPIRES_INLength of time token expires in.static StringGRANT_TYPEType of grant.static StringHTTP_GETHTTP GET.static StringHTTP_POSTHTTP POST.protected HandlerhttpHandlerHandlerto be used to make http requests.static StringLANDING_PAGEURI where the user agent will be directed to after OAuth interaction is complete.static StringPKCE_CODE_CHALLENGEPKCE code challenge parameter.static StringPKCE_CODE_CHALLENGE_METHODPKCE code challenge method.static StringPKCE_CODE_VERIFIERPKCE code verifier parameter.protected SecureRandomrandomSecureRandomused to generate opaque, cryptographically secure strings.static StringREDIRECT_URIUri to redirect the user agent back to from the authorization server.static StringREFRESH_TOKENToken used specifically to retrieve access tokens.static StringRESPONSE_MODEResponse mode https://openid.net/specs/oauth-v2-form-post-response-mode-1_0.html.static StringRESPONSE_TYPEValue that determines the authorization processing flow to be used.static StringSCOPEe.g.static StringSTATEOpaque value used to maintain state between the request and the callback.static StringTOKENToken parameter.static StringTOKEN_TYPEThe type of token used for authentication, AccessToken, OIDC Token or Auth Code.static StringTOKEN_TYPE_HINTA hint about the type of the token submitted for introspection.
-
Constructor Summary
Constructors Constructor Description OAuth2Client(Handler httpHandler, T config, Clock clock, SecureRandom random)Constructs an OAuth2Client using a providedHandlerandOAuthClientConfiguration.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description protected StringcreateAuthorizationState()g Generates a SecureRandom BigInteger as a String.protected URIcreateAuthRedirectUri(String state)Deprecated.UsecreateAuthRedirectUri(String, String)and specify a PKCE challenge.protected URIcreateAuthRedirectUri(String state, String pkceChallenge)Creates aURIthat the user agent will be redirected to for authentication and authorization.protected StringcreatePkceVerifier()Generates a secure opaque PKCE verifier value.protected Function<Void,JsonValue,OAuthException>createPostAuthResponse(JsonValue storedData)Creates the post auth response.protected Promise<JsonValue,OAuthException>createPostResponse(DataStore dataStore, JsonValue storedData)Creates the post response.protected Promise<Request,OAuthException>createRequestForIntrospectEndpoint(String accessToken)Creates aRequestfor the introspect endpoint of an identity provider.protected Promise<Request,OAuthException>createRequestForTokenEndpoint(String code)Deprecated.UsecreateAuthRedirectUri(String, String)and specify a PKCE verifier.protected Promise<Request,OAuthException>createRequestForTokenEndpoint(String code, String pkceVerifier)Creates aRequestfor the token endpoint of an identity provider.protected Promise<Request,OAuthException>createRequestForTokenRefresh(JsonValue storedData)Creates aRequestfor the token refresh endpoint of an identity provider.protected RequestcreateRequestForUserInfoEndpoint(String accessToken)Creates aRequestfor the user information endpoint of an identity provider.protected static StringgetAccessToken(JsonValue data)Retrieves an access token from aJsonValue.protected Promise<JsonValue,OAuthException>getAccessTokenInfo(Context context, String accessToken)Retrieves the access token information as aJsonValue.Promise<URI,OAuthException>getAuthRedirect(DataStore dataStore, String data, URI landingPage)Return the URI that the user agent should be redirected to, to authenticate and authorize access.protected TgetConfig()Gets the configuration for thisOAuthClient.protected static StringgetFirstValueOrNull(List<String> values)Gets the first value out of the List.Promise<? extends OAuth2SessionInfo,OAuthException>getSessionInfo(DataStore dataStore)Validate whether an Auth Server session is still active and valid.protected HandlergetTokenEndpointHandler()The token endpoint handler which wraps the client authentication filter which is capable of adding the client credentials to the request.Promise<UserInfo,OAuthException>getUserInfo(DataStore dataStore)Return the authenticated user's info from the external authentication server.Promise<JsonValue,OAuthException>handleNativePostAuth(Context context, DataStore dataStore, Map<String,List<String>> parameters)Handle the data produced by the Auth Server as a result of a successful authentication and return the final redirect to the mobile device.Promise<JsonValue,OAuthException>handlePostAuth(DataStore dataStore, Map<String,List<String>> requestParameters)Handle the data produced by the Auth Server as a result of a successful authentication and return the final redirect to the landing page specified in theOAuthClient.getAuthRedirect(DataStore, String, URI)call.protected static AsyncFunction<Response,JsonValue,OAuthException>mapToJsonValue()AnAsyncFunctionthat handles aResponsefrom an Auth Server that returns the HTTP entity content as JsonValue, and throws anOAuthExceptionif the response is not successful (200 family status code), or if the content is not a valid JSON.protected Function<JsonValue,UserInfo,OAuthException>mapToUserInfo()Creates aOAuth2UserInfousing a users raw profile.Promise<Void,OAuthException>refresh(DataStore dataStore)Refreshes a token if it has expired.protected Function<JsonValue,Void,OAuthException>storeResponse(DataStore dataStore)Stores all the information received from an authentication or authorization server.protected static <T> Function<NoSuchSecretException,T,OAuthException>throwIfNoClientSecret()Handles a missing client secret.protected Function<JsonValue,JsonValue,OAuthException>validateClientId(DataStore dataStore, JsonValue storedData, String inputToken)Compare client_id from access token associated data with configured client_id.
-
-
-
Field Detail
-
CLIENT_ID
public static final String CLIENT_ID
Client Identifier.- See Also:
- Constant Field Values
-
CLIENT_SECRET
public static final String CLIENT_SECRET
Client Password.- See Also:
- Constant Field Values
-
REDIRECT_URI
public static final String REDIRECT_URI
Uri to redirect the user agent back to from the authorization server.- See Also:
- Constant Field Values
-
GRANT_TYPE
public static final String GRANT_TYPE
Type of grant.- See Also:
- Constant Field Values
-
RESPONSE_TYPE
public static final String RESPONSE_TYPE
Value that determines the authorization processing flow to be used.- See Also:
- Constant Field Values
-
AUTHORIZATION_CODE
public static final String AUTHORIZATION_CODE
String used to verify the resource owner who granted the authorization at the authorization server.- See Also:
- Constant Field Values
-
SCOPE
public static final String SCOPE
e.g. mail, profile, openid, etc.- See Also:
- Constant Field Values
-
STATE
public static final String STATE
Opaque value used to maintain state between the request and the callback.- See Also:
- Constant Field Values
-
PKCE_CODE_CHALLENGE
public static final String PKCE_CODE_CHALLENGE
PKCE code challenge parameter.- See Also:
- Constant Field Values
-
PKCE_CODE_VERIFIER
public static final String PKCE_CODE_VERIFIER
PKCE code verifier parameter.- See Also:
- Constant Field Values
-
PKCE_CODE_CHALLENGE_METHOD
public static final String PKCE_CODE_CHALLENGE_METHOD
PKCE code challenge method.- See Also:
- Constant Field Values
-
TOKEN
public static final String TOKEN
Token parameter.- See Also:
- Constant Field Values
-
RESPONSE_MODE
public static final String RESPONSE_MODE
Response mode https://openid.net/specs/oauth-v2-form-post-response-mode-1_0.html.- See Also:
- Constant Field Values
-
ACCESS_TOKEN
public static final String ACCESS_TOKEN
The access token issued by the authorization server.- See Also:
- Constant Field Values
-
REFRESH_TOKEN
public static final String REFRESH_TOKEN
Token used specifically to retrieve access tokens.- See Also:
- Constant Field Values
-
CODE
public static final String CODE
A type of response_type.- See Also:
- Constant Field Values
-
EXPIRES_IN
public static final String EXPIRES_IN
Length of time token expires in.- See Also:
- Constant Field Values
-
TOKEN_TYPE_HINT
public static final String TOKEN_TYPE_HINT
A hint about the type of the token submitted for introspection.- See Also:
- Constant Field Values
-
TOKEN_TYPE
public static final String TOKEN_TYPE
The type of token used for authentication, AccessToken, OIDC Token or Auth Code.- See Also:
- Constant Field Values
-
DATA
public static final String DATA
URI safe data that MUST not be modified by the client and stored in theDataStore.- See Also:
- Constant Field Values
-
LANDING_PAGE
public static final String LANDING_PAGE
URI where the user agent will be directed to after OAuth interaction is complete.- See Also:
- Constant Field Values
-
EXPIRE_TIME
public static final String EXPIRE_TIME
Expire time.- See Also:
- Constant Field Values
-
AUTHORIZATION_HEADER
public static final String AUTHORIZATION_HEADER
Authorization header.- See Also:
- Constant Field Values
-
ACCEPT_HEADER
public static final String ACCEPT_HEADER
Accept header.- See Also:
- Constant Field Values
-
APPLICATION_JSON
public static final String APPLICATION_JSON
application/json.- See Also:
- Constant Field Values
-
BASIC_AUTH
public static final String BASIC_AUTH
Basic Auth.- See Also:
- Constant Field Values
-
BEARER_TOKEN
public static final String BEARER_TOKEN
Token Type.- See Also:
- Constant Field Values
-
HTTP_GET
public static final String HTTP_GET
HTTP GET.- See Also:
- Constant Field Values
-
HTTP_POST
public static final String HTTP_POST
HTTP POST.- See Also:
- Constant Field Values
-
addExpireTime
protected final Function<JsonValue,JsonValue,OAuthException> addExpireTime
Adds the actual time the token expires.
-
random
protected final SecureRandom random
SecureRandomused to generate opaque, cryptographically secure strings.
-
-
Constructor Detail
-
OAuth2Client
public OAuth2Client(Handler httpHandler, T config, Clock clock, SecureRandom random)
Constructs an OAuth2Client using a providedHandlerandOAuthClientConfiguration.- Parameters:
httpHandler- Handler used to make Http calls to auth and resource servers.config- configuration that will be used to drive oauth flow.clock- clock instancerandom- used to generate opaque, cryptographically secure strings.
-
-
Method Detail
-
mapToJsonValue
protected static AsyncFunction<Response,JsonValue,OAuthException> mapToJsonValue()
AnAsyncFunctionthat handles aResponsefrom an Auth Server that returns the HTTP entity content as JsonValue, and throws anOAuthExceptionif the response is not successful (200 family status code), or if the content is not a valid JSON.- Returns:
- response entity as a JsonValue.
-
getAccessToken
protected static final String getAccessToken(JsonValue data) throws OAuthException
Retrieves an access token from aJsonValue.- Parameters:
data- the JsonValue that may contain an access token.- Returns:
- the access token.
- Throws:
OAuthException- if no access token is found in the JsonValue.
-
getAccessTokenInfo
protected Promise<JsonValue,OAuthException> getAccessTokenInfo(Context context, String accessToken)
Retrieves the access token information as aJsonValue. Invokes the introspection endpoint to validate the access token and returns a JSON [RFC7159] document representing the meta information surrounding the token, including whether this token is currently active. See RFC 7662.- Parameters:
context- Context chain used to keep a relationship between requests (tracking).accessToken- the accessToken to be submitted.- Returns:
- the meta information associated with the access token.
-
getFirstValueOrNull
protected static final String getFirstValueOrNull(List<String> values)
Gets the first value out of the List.- Parameters:
values-List<String>- Returns:
- The first value, or null if none exist.
-
mapToUserInfo
protected final Function<JsonValue,UserInfo,OAuthException> mapToUserInfo()
Creates aOAuth2UserInfousing a users raw profile.- Returns:
- OAuth2UserInfo
-
getAuthRedirect
public Promise<URI,OAuthException> getAuthRedirect(DataStore dataStore, String data, URI landingPage)
Description copied from interface:OAuthClientReturn the URI that the user agent should be redirected to, to authenticate and authorize access.- Specified by:
getAuthRedirectin interfaceOAuthClient- Parameters:
dataStore- The data store that contains information about the OAuth interaction.data- A value which will be stored in the data store to be returned as part of the final landing page redirect response, this MUST be URI safe.landingPage- The final page a user agent should be sent following successful authentication.- Returns:
Promise, with a type ofURI, suitable for redirecting the user agent for external authentication and authorization and anPromise, with a type ofOAuthException, when an error occurs.
-
handlePostAuth
public Promise<JsonValue,OAuthException> handlePostAuth(DataStore dataStore, Map<String,List<String>> requestParameters)
Description copied from interface:OAuthClientHandle the data produced by the Auth Server as a result of a successful authentication and return the final redirect to the landing page specified in theOAuthClient.getAuthRedirect(DataStore, String, URI)call. Validate the request as secure. The returnedJsonValueresponse will also contain the data passed toOAuthClient.getAuthRedirect(DataStore, String, URI).- Specified by:
handlePostAuthin interfaceOAuthClient- Parameters:
dataStore- The data store that contains information about the OAuth interaction.requestParameters- The request parameters containing the data produced by the external authentication server.- Returns:
Promise, with a type ofJsonValue, containing the landing page and the data value that was stored in the data store during theOAuthClient.getAuthRedirect(DataStore, String, URI)call;Promise, with a type ofOAuthException, when an error occurs.
-
handleNativePostAuth
public Promise<JsonValue,OAuthException> handleNativePostAuth(Context context, DataStore dataStore, Map<String,List<String>> parameters)
Description copied from interface:OAuthClientHandle the data produced by the Auth Server as a result of a successful authentication and return the final redirect to the mobile device. Validate the request as secure. The returnedJsonValueresponse will also contain the data passed toOAuthClient.getAuthRedirect(DataStore, String, URI).- Specified by:
handleNativePostAuthin interfaceOAuthClient- Parameters:
context- Context chain used to keep a relationship between requests (tracking)dataStore- The data store that contains information about the OAuth interaction.parameters- The parameters containing the data sent by the external mobile device.- Returns:
Promise, with a type ofJsonValue, containing the data value that was stored in the data store during theOAuthClient.getAuthRedirect(DataStore, String, URI)call;Promise, with a type ofOAuthException, when an error occurs.
-
validateClientId
protected Function<JsonValue,JsonValue,OAuthException> validateClientId(DataStore dataStore, JsonValue storedData, String inputToken)
Compare client_id from access token associated data with configured client_id.- Parameters:
dataStore- data store in which to store the information.storedData- data that is in the storage implementation ofDataStore.inputToken- the token that needs to be inspected.- Returns:
- result of the access token validation.
-
getSessionInfo
public Promise<? extends OAuth2SessionInfo,OAuthException> getSessionInfo(DataStore dataStore)
Description copied from interface:OAuthClientValidate whether an Auth Server session is still active and valid.- Specified by:
getSessionInfoin interfaceOAuthClient- Parameters:
dataStore- The data store that contains information about the OAuth interaction.- Returns:
Promise, with a type ofSessionInfo, representing information about the session.Promise, with a type ofOAuthException, when an error occurs.
-
getUserInfo
public Promise<UserInfo,OAuthException> getUserInfo(DataStore dataStore)
Description copied from interface:OAuthClientReturn the authenticated user's info from the external authentication server.- Specified by:
getUserInfoin interfaceOAuthClient- Parameters:
dataStore- The data store that contains information about the OAuth interaction.- Returns:
Promise, with a type ofUserInfo, containing the available user info.Promise, with a type ofOAuthException, when an error occurs.
-
refresh
public Promise<Void,OAuthException> refresh(DataStore dataStore)
Description copied from interface:OAuthClientRefreshes a token if it has expired.- Specified by:
refreshin interfaceOAuthClient- Parameters:
dataStore- The data store that contains information about the OAuth interaction.- Returns:
PromiseIf a new token has been retrieved, update the data store with the new token.OAuthExceptionwhen an error occurs.
-
getTokenEndpointHandler
protected Handler getTokenEndpointHandler()
The token endpoint handler which wraps the client authentication filter which is capable of adding the client credentials to the request.- Returns:
- the token end point handler.
-
createAuthRedirectUri
protected URI createAuthRedirectUri(String state, String pkceChallenge)
Creates aURIthat the user agent will be redirected to for authentication and authorization.- Parameters:
state- opaque value used to prevent CSRF attacks.pkceChallenge- opaque PKCE challenge used to prevent code interception/injection attacks.- Returns:
- URI
-
createAuthRedirectUri
@Deprecated protected URI createAuthRedirectUri(String state)
Deprecated.UsecreateAuthRedirectUri(String, String)and specify a PKCE challenge.Creates aURIthat the user agent will be redirected to for authentication and authorization.- Parameters:
state- opaque value used to prevent CSRF attacks.- Returns:
- URI
-
createRequestForTokenRefresh
protected Promise<Request,OAuthException> createRequestForTokenRefresh(JsonValue storedData)
Creates aRequestfor the token refresh endpoint of an identity provider.
-
createRequestForUserInfoEndpoint
protected Request createRequestForUserInfoEndpoint(String accessToken)
Creates aRequestfor the user information endpoint of an identity provider.- Parameters:
accessToken- token required to retrieve user information.- Returns:
Requestfor the user information endpoint.
-
createRequestForTokenEndpoint
protected Promise<Request,OAuthException> createRequestForTokenEndpoint(String code, String pkceVerifier)
Creates aRequestfor the token endpoint of an identity provider.- Parameters:
code- e.g authorization_code, received from identity provider during authentication and authorization phase.pkceVerifier- the PKCE verifier, or null if PKCE not being used.- Returns:
Requestfor the token endpoint.
-
createRequestForTokenEndpoint
@Deprecated protected Promise<Request,OAuthException> createRequestForTokenEndpoint(String code)
Deprecated.UsecreateAuthRedirectUri(String, String)and specify a PKCE verifier.Creates aRequestfor the token endpoint of an identity provider.- Parameters:
code- e.g authorization_code, received from identity provider during authentication and authorization phase.- Returns:
Requestfor the token endpoint.
-
createRequestForIntrospectEndpoint
protected Promise<Request,OAuthException> createRequestForIntrospectEndpoint(String accessToken)
Creates aRequestfor the introspect endpoint of an identity provider. See RFC 7662 Section 2.1.- Parameters:
accessToken- token required to retrieve user information.- Returns:
Requestfor the introspect endpoint.
-
storeResponse
protected final Function<JsonValue,Void,OAuthException> storeResponse(DataStore dataStore)
Stores all the information received from an authentication or authorization server.- Parameters:
dataStore- data store in which to store the information.- Returns:
- Void when storage is complete.
-
throwIfNoClientSecret
protected static <T> Function<NoSuchSecretException,T,OAuthException> throwIfNoClientSecret()
Handles a missing client secret.- Type Parameters:
T- the expected return type.- Returns:
- a function that will handle a missing client secret by throwing an OAuthConfigException.
-
createPostAuthResponse
protected final Function<Void,JsonValue,OAuthException> createPostAuthResponse(JsonValue storedData)
Creates the post auth response.- Parameters:
storedData- data store that contains information about the OAuth interaction.- Returns:
- the 'landingPage' and the 'data' as a JsonValue.
-
createPostResponse
protected Promise<JsonValue,OAuthException> createPostResponse(DataStore dataStore, JsonValue storedData) throws OAuthException
Creates the post response.- Parameters:
dataStore- data store in which to store the information.storedData- data store that contains information about the OAuth interaction.- Returns:
- the 'data' as a JsonValue.
- Throws:
OAuthException- if could not retrieve data from DataStore
-
getConfig
protected T getConfig()
Gets the configuration for thisOAuthClient.- Returns:
- the configuration used to configure this client.
-
createAuthorizationState
protected String createAuthorizationState()
g Generates a SecureRandom BigInteger as a String.- Returns:
- random BigInteger as a String.
-
createPkceVerifier
protected String createPkceVerifier()
Generates a secure opaque PKCE verifier value. See RFC 7636 Section 4.1- Returns:
- the random PKCE verifier.
-
-