Class Credential
- java.lang.Object
-
- com.google.api.client.auth.oauth2.Credential
-
- All Implemented Interfaces:
com.google.api.client.http.HttpExecuteInterceptor,com.google.api.client.http.HttpRequestInitializer,com.google.api.client.http.HttpUnsuccessfulResponseHandler
public class Credential extends java.lang.Object implements com.google.api.client.http.HttpExecuteInterceptor, com.google.api.client.http.HttpRequestInitializer, com.google.api.client.http.HttpUnsuccessfulResponseHandlerThread-safe OAuth 2.0 helper for accessing protected resources using an access token, as well as optionally refreshing the access token when it expires using a refresh token.Sample usage:
public static Credential createCredentialWithAccessTokenOnly( HttpTransport transport, JsonFactory jsonFactory, TokenResponse tokenResponse) { return new Credential(BearerToken.authorizationHeaderAccessMethod()).setFromTokenResponse( tokenResponse); } public static Credential createCredentialWithRefreshToken( HttpTransport transport, JsonFactory jsonFactory, TokenResponse tokenResponse) { return new Credential.Builder(BearerToken.authorizationHeaderAccessMethod()).setTransport( transport) .setJsonFactory(jsonFactory) .setTokenServerUrl( new GenericUrl("https://server.example.com/token")) .setClientAuthentication(new BasicAuthentication("s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw")) .build() .setFromTokenResponse(tokenResponse); }If you need to persist the access token in a data store, use
DataStoreFactoryandCredential.Builder.addRefreshListener(CredentialRefreshListener)withDataStoreCredentialRefreshListener.If you have a custom request initializer, request execute interceptor, or unsuccessful response handler, take a look at the sample usage for
HttpExecuteInterceptorandHttpUnsuccessfulResponseHandler, which are interfaces that this class also implements.- Since:
- 1.7
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static interfaceCredential.AccessMethodMethod of presenting the access token to the resource server as specified in Accessing Protected Resources.static classCredential.BuilderCredential builder.
-
Field Summary
Fields Modifier and Type Field Description private java.lang.StringaccessTokenAccess token issued by the authorization server.private com.google.api.client.http.HttpExecuteInterceptorclientAuthenticationClient authentication ornullfor none.private com.google.api.client.util.ClockclockClock used to provide the currentMillis.private java.lang.LongexpirationTimeMillisecondsExpected expiration time in milliseconds based onsetExpiresInSeconds(java.lang.Long)ornullfor none.private com.google.api.client.json.JsonFactoryjsonFactoryJSON factory to use for parsing response for refresh token request ornullfor none.private java.util.concurrent.locks.LocklockLock on the token response information.(package private) static java.util.logging.LoggerLOGGERprivate Credential.AccessMethodmethodMethod of presenting the access token to the resource server (for exampleBearerToken.AuthorizationHeaderAccessMethod).private java.util.Collection<CredentialRefreshListener>refreshListenersUnmodifiable collection of listeners for refresh token results.private java.lang.StringrefreshTokenRefresh token which can be used to obtain new access tokens using the same authorization grant ornullfor none.private com.google.api.client.http.HttpRequestInitializerrequestInitializerHTTP request initializer for refresh token requests to the token server ornullfor none.private java.lang.StringtokenServerEncodedUrlEncoded token server URL ornullfor none.private com.google.api.client.http.HttpTransporttransportHTTP transport for executing refresh token request ornullfor none.
-
Constructor Summary
Constructors Modifier Constructor Description Credential(Credential.AccessMethod method)Constructor with the ability to access protected resources, but not refresh tokens.protectedCredential(Credential.Builder builder)
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description protected TokenResponseexecuteRefreshToken()Executes a request for new credentials from the token server.java.lang.StringgetAccessToken()Returns the access token ornullfor none.com.google.api.client.http.HttpExecuteInterceptorgetClientAuthentication()Returns the client authentication ornullfor none.com.google.api.client.util.ClockgetClock()Returns the clock used for expiration checks by this Credential.java.lang.LonggetExpirationTimeMilliseconds()Expected expiration time in milliseconds ornullfor none.java.lang.LonggetExpiresInSeconds()Returns the remaining lifetime in seconds of the access token (for example 3600 for an hour, or -3600 if expired an hour ago) ornullif unknown.com.google.api.client.json.JsonFactorygetJsonFactory()Returns the JSON factory to use for parsing response for refresh token request ornullfor none.Credential.AccessMethodgetMethod()Return the method of presenting the access token to the resource server (for exampleBearerToken.AuthorizationHeaderAccessMethod).java.util.Collection<CredentialRefreshListener>getRefreshListeners()Returns the unmodifiable collection of listeners for refresh token results.java.lang.StringgetRefreshToken()Returns the refresh token associated with the access token to be refreshed ornullfor none.com.google.api.client.http.HttpRequestInitializergetRequestInitializer()Returns the HTTP request initializer for refresh token requests to the token server ornullfor none.java.lang.StringgetTokenServerEncodedUrl()Returns the encoded authorization server URL ornullfor none.com.google.api.client.http.HttpTransportgetTransport()Return the HTTP transport for executing refresh token request ornullfor none.booleanhandleResponse(com.google.api.client.http.HttpRequest request, com.google.api.client.http.HttpResponse response, boolean supportsRetry)voidinitialize(com.google.api.client.http.HttpRequest request)voidintercept(com.google.api.client.http.HttpRequest request)booleanrefreshToken()Request a new access token from the authorization endpoint.CredentialsetAccessToken(java.lang.String accessToken)Sets the access token.CredentialsetExpirationTimeMilliseconds(java.lang.Long expirationTimeMilliseconds)Sets the expected expiration time in milliseconds ornullfor none.CredentialsetExpiresInSeconds(java.lang.Long expiresIn)Sets the lifetime in seconds of the access token (for example 3600 for an hour) ornullfor none.CredentialsetFromTokenResponse(TokenResponse tokenResponse)Sets theaccess token,refresh token(if available), andexpires-in timebased on the values from the token response.CredentialsetRefreshToken(java.lang.String refreshToken)Sets the refresh token.
-
-
-
Field Detail
-
LOGGER
static final java.util.logging.Logger LOGGER
-
lock
private final java.util.concurrent.locks.Lock lock
Lock on the token response information.
-
method
private final Credential.AccessMethod method
Method of presenting the access token to the resource server (for exampleBearerToken.AuthorizationHeaderAccessMethod).
-
clock
private final com.google.api.client.util.Clock clock
Clock used to provide the currentMillis.
-
accessToken
private java.lang.String accessToken
Access token issued by the authorization server.
-
expirationTimeMilliseconds
private java.lang.Long expirationTimeMilliseconds
Expected expiration time in milliseconds based onsetExpiresInSeconds(java.lang.Long)ornullfor none.
-
refreshToken
private java.lang.String refreshToken
Refresh token which can be used to obtain new access tokens using the same authorization grant ornullfor none.
-
transport
private final com.google.api.client.http.HttpTransport transport
HTTP transport for executing refresh token request ornullfor none.
-
clientAuthentication
private final com.google.api.client.http.HttpExecuteInterceptor clientAuthentication
Client authentication ornullfor none.
-
jsonFactory
private final com.google.api.client.json.JsonFactory jsonFactory
JSON factory to use for parsing response for refresh token request ornullfor none.
-
tokenServerEncodedUrl
private final java.lang.String tokenServerEncodedUrl
Encoded token server URL ornullfor none.
-
refreshListeners
private final java.util.Collection<CredentialRefreshListener> refreshListeners
Unmodifiable collection of listeners for refresh token results.
-
requestInitializer
private final com.google.api.client.http.HttpRequestInitializer requestInitializer
HTTP request initializer for refresh token requests to the token server ornullfor none.
-
-
Constructor Detail
-
Credential
public Credential(Credential.AccessMethod method)
Constructor with the ability to access protected resources, but not refresh tokens.To use with the ability to refresh tokens, use
Credential.Builder.- Parameters:
method- method of presenting the access token to the resource server (for exampleBearerToken.AuthorizationHeaderAccessMethod)
-
Credential
protected Credential(Credential.Builder builder)
- Parameters:
builder- credential builder- Since:
- 1.14
-
-
Method Detail
-
intercept
public void intercept(com.google.api.client.http.HttpRequest request) throws java.io.IOExceptionDefault implementation is to try to refresh the access token if there is no access token or if we are 1 minute away from expiration. If token server is unavailable, it will try to use the access token even if has expired. If a 4xx error is encountered while refreshing the token,
TokenResponseExceptionis thrown. If successful, it will callgetMethod()andCredential.AccessMethod.intercept(com.google.api.client.http.HttpRequest, java.lang.String).Subclasses may override.
- Specified by:
interceptin interfacecom.google.api.client.http.HttpExecuteInterceptor- Throws:
java.io.IOException
-
handleResponse
public boolean handleResponse(com.google.api.client.http.HttpRequest request, com.google.api.client.http.HttpResponse response, boolean supportsRetry)Default implementation checks if
WWW-Authenticateexists and contains a "Bearer" value (see rfc6750 section 3.1 for more details). If so, it callsrefreshTokenin case the error code containsinvalid_token. If there is no "Bearer" inWWW-Authenticateand the status code isHttpStatusCodes.STATUS_CODE_UNAUTHORIZEDit callsrefreshToken. IfexecuteRefreshToken()throws an I/O exception, this implementation will log the exception and returnfalse. Subclasses may override.- Specified by:
handleResponsein interfacecom.google.api.client.http.HttpUnsuccessfulResponseHandler
-
initialize
public void initialize(com.google.api.client.http.HttpRequest request) throws java.io.IOException- Specified by:
initializein interfacecom.google.api.client.http.HttpRequestInitializer- Throws:
java.io.IOException
-
getAccessToken
public final java.lang.String getAccessToken()
Returns the access token ornullfor none.
-
setAccessToken
public Credential setAccessToken(java.lang.String accessToken)
Sets the access token.Overriding is only supported for the purpose of calling the super implementation and changing the return type, but nothing else.
- Parameters:
accessToken- access token ornullfor none
-
getMethod
public final Credential.AccessMethod getMethod()
Return the method of presenting the access token to the resource server (for exampleBearerToken.AuthorizationHeaderAccessMethod).
-
getClock
public final com.google.api.client.util.Clock getClock()
Returns the clock used for expiration checks by this Credential. Mostly used for unit-testing.- Since:
- 1.9
-
getTransport
public final com.google.api.client.http.HttpTransport getTransport()
Return the HTTP transport for executing refresh token request ornullfor none.
-
getJsonFactory
public final com.google.api.client.json.JsonFactory getJsonFactory()
Returns the JSON factory to use for parsing response for refresh token request ornullfor none.
-
getTokenServerEncodedUrl
public final java.lang.String getTokenServerEncodedUrl()
Returns the encoded authorization server URL ornullfor none.
-
getRefreshToken
public final java.lang.String getRefreshToken()
Returns the refresh token associated with the access token to be refreshed ornullfor none.
-
setRefreshToken
public Credential setRefreshToken(java.lang.String refreshToken)
Sets the refresh token.Overriding is only supported for the purpose of calling the super implementation and changing the return type, but nothing else.
- Parameters:
refreshToken- refresh token ornullfor none
-
getExpirationTimeMilliseconds
public final java.lang.Long getExpirationTimeMilliseconds()
Expected expiration time in milliseconds ornullfor none.
-
setExpirationTimeMilliseconds
public Credential setExpirationTimeMilliseconds(java.lang.Long expirationTimeMilliseconds)
Sets the expected expiration time in milliseconds ornullfor none.Overriding is only supported for the purpose of calling the super implementation and changing the return type, but nothing else.
-
getExpiresInSeconds
public final java.lang.Long getExpiresInSeconds()
Returns the remaining lifetime in seconds of the access token (for example 3600 for an hour, or -3600 if expired an hour ago) ornullif unknown.
-
setExpiresInSeconds
public Credential setExpiresInSeconds(java.lang.Long expiresIn)
Sets the lifetime in seconds of the access token (for example 3600 for an hour) ornullfor none.Overriding is only supported for the purpose of calling the super implementation and changing the return type, but nothing else.
- Parameters:
expiresIn- lifetime in seconds of the access token (for example 3600 for an hour) ornullfor none
-
getClientAuthentication
public final com.google.api.client.http.HttpExecuteInterceptor getClientAuthentication()
Returns the client authentication ornullfor none.
-
getRequestInitializer
public final com.google.api.client.http.HttpRequestInitializer getRequestInitializer()
Returns the HTTP request initializer for refresh token requests to the token server ornullfor none.
-
refreshToken
public final boolean refreshToken() throws java.io.IOExceptionRequest a new access token from the authorization endpoint.On success, it will call
setFromTokenResponse(TokenResponse), callCredentialRefreshListener.onTokenResponse(com.google.api.client.auth.oauth2.Credential, com.google.api.client.auth.oauth2.TokenResponse)with the token response, and returntrue. On error, it will callsetAccessToken(String)andsetExpiresInSeconds(Long)withnull, callCredentialRefreshListener.onTokenErrorResponse(com.google.api.client.auth.oauth2.Credential, com.google.api.client.auth.oauth2.TokenErrorResponse)with the token error response, and returnfalse. If a 4xx error is encountered while refreshing the token,TokenResponseExceptionis thrown.If there is no refresh token, it will quietly return
false.- Returns:
- whether a new access token was successfully retrieved
- Throws:
java.io.IOException
-
setFromTokenResponse
public Credential setFromTokenResponse(TokenResponse tokenResponse)
Sets theaccess token,refresh token(if available), andexpires-in timebased on the values from the token response.It does not call the refresh listeners.
Overriding is only supported for the purpose of calling the super implementation and changing the return type, but nothing else.
- Parameters:
tokenResponse- successful token response
-
executeRefreshToken
protected TokenResponse executeRefreshToken() throws java.io.IOException
Executes a request for new credentials from the token server.The default implementation calls
TokenRequest.execute()using thegetTransport(),getJsonFactory(),getRequestInitializer(),getTokenServerEncodedUrl(),getRefreshToken(), and thegetClientAuthentication(). IfgetRefreshToken()isnull, it instead returnsnull.Subclasses may override for a different implementation. Implementations can assume proper thread synchronization is already taken care of inside
refreshToken().- Returns:
- successful response from the token server or
nullif it is not possible to refresh the access token - Throws:
TokenResponseException- if an error response was received from the token serverjava.io.IOException
-
getRefreshListeners
public final java.util.Collection<CredentialRefreshListener> getRefreshListeners()
Returns the unmodifiable collection of listeners for refresh token results.
-
-