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 interface
Method of presenting the access token to the resource server as specified in Accessing Protected Resources.static class
Credential builder. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate String
Access token issued by the authorization server.private final com.google.api.client.http.HttpExecuteInterceptor
Client authentication ornull
for none.private final com.google.api.client.util.Clock
Clock used to provide the currentMillis.private Long
Expected expiration time in milliseconds based onsetExpiresInSeconds(java.lang.Long)
ornull
for none.private final com.google.api.client.json.JsonFactory
JSON factory to use for parsing response for refresh token request ornull
for none.private final Lock
Lock on the token response information.(package private) static final Logger
private final Credential.AccessMethod
Method 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 String
Refresh token which can be used to obtain new access tokens using the same authorization grant ornull
for none.private final com.google.api.client.http.HttpRequestInitializer
HTTP request initializer for refresh token requests to the token server ornull
for none.private final String
Encoded token server URL ornull
for none.private final com.google.api.client.http.HttpTransport
HTTP transport for executing refresh token request ornull
for none. -
Constructor Summary
ConstructorsModifierConstructorDescriptionCredential
(Credential.AccessMethod method) Constructor with the ability to access protected resources, but not refresh tokens.protected
Credential
(Credential.Builder builder) -
Method Summary
Modifier and TypeMethodDescriptionprotected TokenResponse
Executes a request for new credentials from the token server.final String
Returns the access token ornull
for none.final com.google.api.client.http.HttpExecuteInterceptor
Returns the client authentication ornull
for none.final com.google.api.client.util.Clock
getClock()
Returns the clock used for expiration checks by this Credential.final Long
Expected expiration time in milliseconds ornull
for none.final Long
Returns the remaining lifetime in seconds of the access token (for example 3600 for an hour, or -3600 if expired an hour ago) ornull
if unknown.final com.google.api.client.json.JsonFactory
Returns the JSON factory to use for parsing response for refresh token request ornull
for none.final Credential.AccessMethod
Return 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 String
Returns the refresh token associated with the access token to be refreshed ornull
for none.final com.google.api.client.http.HttpRequestInitializer
Returns the HTTP request initializer for refresh token requests to the token server ornull
for none.final String
Returns the encoded authorization server URL ornull
for none.final com.google.api.client.http.HttpTransport
Return the HTTP transport for executing refresh token request ornull
for none.boolean
handleResponse
(com.google.api.client.http.HttpRequest request, com.google.api.client.http.HttpResponse response, boolean supportsRetry) void
initialize
(com.google.api.client.http.HttpRequest request) void
intercept
(com.google.api.client.http.HttpRequest request) final boolean
Request 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 ornull
for none.setExpiresInSeconds
(Long expiresIn) Sets the lifetime in seconds of the access token (for example 3600 for an hour) ornull
for none.setFromTokenResponse
(TokenResponse tokenResponse) Sets theaccess token
,refresh token
(if available), andexpires-in time
based 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(java.lang.Long)
ornull
for none. -
refreshToken
Refresh token which can be used to obtain new access tokens using the same authorization grant ornull
for none. -
transport
private final com.google.api.client.http.HttpTransport transportHTTP transport for executing refresh token request ornull
for none. -
clientAuthentication
private final com.google.api.client.http.HttpExecuteInterceptor clientAuthenticationClient authentication ornull
for none. -
jsonFactory
private final com.google.api.client.json.JsonFactory jsonFactoryJSON factory to use for parsing response for refresh token request ornull
for none. -
tokenServerEncodedUrl
Encoded token server URL ornull
for 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 ornull
for 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,
TokenResponseException
is thrown. If successful, it will callgetMethod()
andCredential.AccessMethod.intercept(com.google.api.client.http.HttpRequest, java.lang.String)
.Subclasses may override.
- Specified by:
intercept
in 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-Authenticate
exists and contains a "Bearer" value (see rfc6750 section 3.1 for more details). If so, it callsrefreshToken
in case the error code containsinvalid_token
. If there is no "Bearer" inWWW-Authenticate
and the status code isHttpStatusCodes.STATUS_CODE_UNAUTHORIZED
it callsrefreshToken
. IfexecuteRefreshToken()
throws an I/O exception, this implementation will log the exception and returnfalse
. Subclasses may override.- Specified by:
handleResponse
in interfacecom.google.api.client.http.HttpUnsuccessfulResponseHandler
-
initialize
- Specified by:
initialize
in interfacecom.google.api.client.http.HttpRequestInitializer
- Throws:
IOException
-
getAccessToken
Returns the access token ornull
for 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 ornull
for 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 ornull
for none. -
getJsonFactory
public final com.google.api.client.json.JsonFactory getJsonFactory()Returns the JSON factory to use for parsing response for refresh token request ornull
for none. -
getTokenServerEncodedUrl
Returns the encoded authorization server URL ornull
for none. -
getRefreshToken
Returns the refresh token associated with the access token to be refreshed ornull
for 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 ornull
for none
-
getExpirationTimeMilliseconds
Expected expiration time in milliseconds ornull
for none. -
setExpirationTimeMilliseconds
Sets the expected expiration time in milliseconds ornull
for 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) ornull
if unknown. -
setExpiresInSeconds
Sets the lifetime in seconds of the access token (for example 3600 for an hour) ornull
for 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) ornull
for none
-
getClientAuthentication
public final com.google.api.client.http.HttpExecuteInterceptor getClientAuthentication()Returns the client authentication ornull
for none. -
getRequestInitializer
public final com.google.api.client.http.HttpRequestInitializer getRequestInitializer()Returns the HTTP request initializer for refresh token requests to the token server ornull
for none. -
refreshToken
Request 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,TokenResponseException
is 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 time
based 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
null
if 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.
-