Class Credential
- All Implemented Interfaces:
com.google.api.client.http.HttpExecuteInterceptor, com.google.api.client.http.HttpRequestInitializer, com.google.api.client.http.HttpUnsuccessfulResponseHandler
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 DataStoreFactory and
Credential.Builder.addRefreshListener(CredentialRefreshListener) with
DataStoreCredentialRefreshListener.
If you have a custom request initializer, request execute interceptor, or unsuccessful response
handler, take a look at the sample usage for HttpExecuteInterceptor and
HttpUnsuccessfulResponseHandler, which are interfaces that this class also implements.
- Since:
- 1.7
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceMethod of presenting the access token to the resource server as specified in Accessing Protected Resources.static classCredential builder. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate StringAccess token issued by the authorization server.private final com.google.api.client.http.HttpExecuteInterceptorClient authentication ornullfor none.private final com.google.api.client.util.ClockClock used to provide the currentMillis.private LongExpected expiration time in milliseconds based onsetExpiresInSeconds(Long)ornullfor none.private final com.google.api.client.json.JsonFactoryJSON factory to use for parsing response for refresh token request ornullfor none.private final LockLock on the token response information.(package private) static final Loggerprivate final Credential.AccessMethodMethod of presenting the access token to the resource server (for exampleBearerToken.AuthorizationHeaderAccessMethod).private final Collection<CredentialRefreshListener> Unmodifiable collection of listeners for refresh token results.private StringRefresh token which can be used to obtain new access tokens using the same authorization grant ornullfor none.private final com.google.api.client.http.HttpRequestInitializerHTTP request initializer for refresh token requests to the token server ornullfor none.private final StringEncoded token server URL ornullfor none.private final com.google.api.client.http.HttpTransportHTTP transport for executing refresh token request ornullfor none. -
Constructor Summary
ConstructorsModifierConstructorDescriptionCredential(Credential.AccessMethod method) Constructor with the ability to access protected resources, but not refresh tokens.protectedCredential(Credential.Builder builder) -
Method Summary
Modifier and TypeMethodDescriptionprotected TokenResponseExecutes a request for new credentials from the token server.final StringReturns the access token ornullfor none.final com.google.api.client.http.HttpExecuteInterceptorReturns the client authentication ornullfor none.final com.google.api.client.util.ClockgetClock()Returns the clock used for expiration checks by this Credential.final LongExpected expiration time in milliseconds ornullfor none.final LongReturns the remaining lifetime in seconds of the access token (for example 3600 for an hour, or -3600 if expired an hour ago) ornullif unknown.final com.google.api.client.json.JsonFactoryReturns the JSON factory to use for parsing response for refresh token request ornullfor none.final Credential.AccessMethodReturn the method of presenting the access token to the resource server (for exampleBearerToken.AuthorizationHeaderAccessMethod).Returns the unmodifiable collection of listeners for refresh token results.final StringReturns the refresh token associated with the access token to be refreshed ornullfor none.final com.google.api.client.http.HttpRequestInitializerReturns the HTTP request initializer for refresh token requests to the token server ornullfor none.final StringReturns the encoded authorization server URL ornullfor none.final com.google.api.client.http.HttpTransportReturn 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) final booleanRequest a new access token from the authorization endpoint.setAccessToken(String accessToken) Sets the access token.setExpirationTimeMilliseconds(Long expirationTimeMilliseconds) Sets the expected expiration time in milliseconds ornullfor none.setExpiresInSeconds(Long expiresIn) Sets the lifetime in seconds of the access token (for example 3600 for an hour) ornullfor none.setFromTokenResponse(TokenResponse tokenResponse) Sets theaccess token,refresh token(if available), andexpires-in timebased on the values from the token response.setRefreshToken(String refreshToken) Sets the refresh token.
-
Field Details
-
LOGGER
-
lock
Lock on the token response information. -
method
Method of presenting the access token to the resource server (for exampleBearerToken.AuthorizationHeaderAccessMethod). -
clock
private final com.google.api.client.util.Clock clockClock used to provide the currentMillis. -
accessToken
Access token issued by the authorization server. -
expirationTimeMilliseconds
Expected expiration time in milliseconds based onsetExpiresInSeconds(Long)ornullfor none. -
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 transportHTTP transport for executing refresh token request ornullfor none. -
clientAuthentication
private final com.google.api.client.http.HttpExecuteInterceptor clientAuthenticationClient authentication ornullfor none. -
jsonFactory
private final com.google.api.client.json.JsonFactory jsonFactoryJSON factory to use for parsing response for refresh token request ornullfor none. -
tokenServerEncodedUrl
Encoded token server URL ornullfor none. -
refreshListeners
Unmodifiable collection of listeners for refresh token results. -
requestInitializer
private final com.google.api.client.http.HttpRequestInitializer requestInitializerHTTP request initializer for refresh token requests to the token server ornullfor none.
-
-
Constructor Details
-
Credential
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
- Parameters:
builder- credential builder- Since:
- 1.14
-
-
Method Details
-
intercept
Default 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(HttpRequest, String).Subclasses may override.
- Specified by:
interceptin interfacecom.google.api.client.http.HttpExecuteInterceptor- Throws:
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
- Specified by:
initializein interfacecom.google.api.client.http.HttpRequestInitializer- Throws:
IOException
-
getAccessToken
Returns the access token ornullfor none. -
setAccessToken
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
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
Returns the encoded authorization server URL ornullfor none. -
getRefreshToken
Returns the refresh token associated with the access token to be refreshed ornullfor none. -
setRefreshToken
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
Expected expiration time in milliseconds ornullfor none. -
setExpirationTimeMilliseconds
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
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
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
Request a new access token from the authorization endpoint.On success, it will call
setFromTokenResponse(TokenResponse), callCredentialRefreshListener.onTokenResponse(Credential, TokenResponse)with the token response, and returntrue. On error, it will callsetAccessToken(String)andsetExpiresInSeconds(Long)withnull, callCredentialRefreshListener.onTokenErrorResponse(Credential, 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:
IOException
-
setFromTokenResponse
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
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 serverIOException
-
getRefreshListeners
Returns the unmodifiable collection of listeners for refresh token results.
-