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 String
ACCEPT_HEADER
Accept header.static String
ACCESS_TOKEN
The access token issued by the authorization server.protected Function<JsonValue,JsonValue,OAuthException>
addExpireTime
Adds the actual time the token expires.static String
APPLICATION_JSON
application/json.static String
AUTHORIZATION_CODE
String used to verify the resource owner who granted the authorization at the authorization server.static String
AUTHORIZATION_HEADER
Authorization header.static String
BASIC_AUTH
Basic Auth.static String
BEARER_TOKEN
Token Type.static String
CLIENT_ID
Client Identifier.static String
CLIENT_SECRET
Client Password.protected Clock
clock
Clock
used to handle token expire times.static String
CODE
A type of response_type.static String
DATA
URI safe data that MUST not be modified by the client and stored in theDataStore
.static String
EXPIRE_TIME
Expire time.static String
EXPIRES_IN
Length of time token expires in.static String
GRANT_TYPE
Type of grant.static String
HTTP_GET
HTTP GET.static String
HTTP_POST
HTTP POST.protected Handler
httpHandler
Handler
to be used to make http requests.static String
LANDING_PAGE
URI where the user agent will be directed to after OAuth interaction is complete.static String
PKCE_CODE_CHALLENGE
PKCE code challenge parameter.static String
PKCE_CODE_CHALLENGE_METHOD
PKCE code challenge method.static String
PKCE_CODE_VERIFIER
PKCE code verifier parameter.protected SecureRandom
random
SecureRandom
used to generate opaque, cryptographically secure strings.static String
REDIRECT_URI
Uri to redirect the user agent back to from the authorization server.static String
REFRESH_TOKEN
Token used specifically to retrieve access tokens.static String
RESPONSE_MODE
Response mode https://openid.net/specs/oauth-v2-form-post-response-mode-1_0.html.static String
RESPONSE_TYPE
Value that determines the authorization processing flow to be used.static String
SCOPE
e.g.static String
STATE
Opaque value used to maintain state between the request and the callback.static String
TOKEN
Token parameter.static String
TOKEN_TYPE
The type of token used for authentication, AccessToken, OIDC Token or Auth Code.static String
TOKEN_TYPE_HINT
A 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 providedHandler
andOAuthClientConfiguration
.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description protected String
createAuthorizationState()
g Generates a SecureRandom BigInteger as a String.protected URI
createAuthRedirectUri(String state)
Deprecated.UsecreateAuthRedirectUri(String, String)
and specify a PKCE challenge.protected URI
createAuthRedirectUri(String state, String pkceChallenge)
Creates aURI
that the user agent will be redirected to for authentication and authorization.protected String
createPkceVerifier()
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 aRequest
for 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 aRequest
for the token endpoint of an identity provider.protected Promise<Request,OAuthException>
createRequestForTokenRefresh(JsonValue storedData)
Creates aRequest
for the token refresh endpoint of an identity provider.protected Request
createRequestForUserInfoEndpoint(String accessToken)
Creates aRequest
for the user information endpoint of an identity provider.protected static String
getAccessToken(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 T
getConfig()
Gets the configuration for thisOAuthClient
.protected static String
getFirstValueOrNull(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 Handler
getTokenEndpointHandler()
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()
AnAsyncFunction
that handles aResponse
from an Auth Server that returns the HTTP entity content as JsonValue, and throws anOAuthException
if 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 aOAuth2UserInfo
using 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
SecureRandom
used to generate opaque, cryptographically secure strings.
-
-
Constructor Detail
-
OAuth2Client
public OAuth2Client(Handler httpHandler, T config, Clock clock, SecureRandom random)
Constructs an OAuth2Client using a providedHandler
andOAuthClientConfiguration
.- 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()
AnAsyncFunction
that handles aResponse
from an Auth Server that returns the HTTP entity content as JsonValue, and throws anOAuthException
if 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 aOAuth2UserInfo
using a users raw profile.- Returns:
- OAuth2UserInfo
-
getAuthRedirect
public Promise<URI,OAuthException> getAuthRedirect(DataStore dataStore, String data, URI landingPage)
Description copied from interface:OAuthClient
Return the URI that the user agent should be redirected to, to authenticate and authorize access.- Specified by:
getAuthRedirect
in 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:OAuthClient
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. Validate the request as secure. The returnedJsonValue
response will also contain the data passed toOAuthClient.getAuthRedirect(DataStore, String, URI)
.- Specified by:
handlePostAuth
in 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:OAuthClient
Handle 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 returnedJsonValue
response will also contain the data passed toOAuthClient.getAuthRedirect(DataStore, String, URI)
.- Specified by:
handleNativePostAuth
in 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:OAuthClient
Validate whether an Auth Server session is still active and valid.- Specified by:
getSessionInfo
in 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:OAuthClient
Return the authenticated user's info from the external authentication server.- Specified by:
getUserInfo
in 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:OAuthClient
Refreshes a token if it has expired.- Specified by:
refresh
in interfaceOAuthClient
- Parameters:
dataStore
- The data store that contains information about the OAuth interaction.- Returns:
Promise
If a new token has been retrieved, update the data store with the new token.OAuthException
when 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 aURI
that 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 aURI
that 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 aRequest
for the token refresh endpoint of an identity provider.
-
createRequestForUserInfoEndpoint
protected Request createRequestForUserInfoEndpoint(String accessToken)
Creates aRequest
for the user information endpoint of an identity provider.- Parameters:
accessToken
- token required to retrieve user information.- Returns:
Request
for the user information endpoint.
-
createRequestForTokenEndpoint
protected Promise<Request,OAuthException> createRequestForTokenEndpoint(String code, String pkceVerifier)
Creates aRequest
for 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:
Request
for the token endpoint.
-
createRequestForTokenEndpoint
@Deprecated protected Promise<Request,OAuthException> createRequestForTokenEndpoint(String code)
Deprecated.UsecreateAuthRedirectUri(String, String)
and specify a PKCE verifier.Creates aRequest
for the token endpoint of an identity provider.- Parameters:
code
- e.g authorization_code, received from identity provider during authentication and authorization phase.- Returns:
Request
for the token endpoint.
-
createRequestForIntrospectEndpoint
protected Promise<Request,OAuthException> createRequestForIntrospectEndpoint(String accessToken)
Creates aRequest
for the introspect endpoint of an identity provider. See RFC 7662 Section 2.1.- Parameters:
accessToken
- token required to retrieve user information.- Returns:
Request
for 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.
-
-