Class 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.HttpUnsuccessfulResponseHandler
    Thread-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 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
    • 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.
      • 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 on setExpiresInSeconds(java.lang.Long) or null for none.
      • refreshToken

        private java.lang.String refreshToken
        Refresh token which can be used to obtain new access tokens using the same authorization grant or null for none.
      • transport

        private final com.google.api.client.http.HttpTransport transport
        HTTP transport for executing refresh token request or null for none.
      • clientAuthentication

        private final com.google.api.client.http.HttpExecuteInterceptor clientAuthentication
        Client authentication or null for none.
      • jsonFactory

        private final com.google.api.client.json.JsonFactory jsonFactory
        JSON factory to use for parsing response for refresh token request or null for none.
      • tokenServerEncodedUrl

        private final java.lang.String tokenServerEncodedUrl
        Encoded token server URL or null for 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 or null for none.
    • Method Detail

      • intercept

        public void intercept​(com.google.api.client.http.HttpRequest request)
                       throws java.io.IOException

        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 call getMethod() and Credential.AccessMethod.intercept(com.google.api.client.http.HttpRequest, java.lang.String).

        Subclasses may override.

        Specified by:
        intercept in interface com.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-Authenticate exists and contains a "Bearer" value (see rfc6750 section 3.1 for more details). If so, it calls refreshToken in case the error code contains invalid_token. If there is no "Bearer" in WWW-Authenticate and the status code is HttpStatusCodes.STATUS_CODE_UNAUTHORIZED it calls refreshToken. If executeRefreshToken() throws an I/O exception, this implementation will log the exception and return false. Subclasses may override.

        Specified by:
        handleResponse in interface com.google.api.client.http.HttpUnsuccessfulResponseHandler
      • initialize

        public void initialize​(com.google.api.client.http.HttpRequest request)
                        throws java.io.IOException
        Specified by:
        initialize in interface com.google.api.client.http.HttpRequestInitializer
        Throws:
        java.io.IOException
      • getAccessToken

        public final java.lang.String getAccessToken()
        Returns the access token or null for 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 or null for none
      • 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 or null 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 or null for none.
      • getTokenServerEncodedUrl

        public final java.lang.String getTokenServerEncodedUrl()
        Returns the encoded authorization server URL or null for none.
      • getRefreshToken

        public final java.lang.String getRefreshToken()
        Returns the refresh token associated with the access token to be refreshed or null for 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 or null for none
      • getExpirationTimeMilliseconds

        public final java.lang.Long getExpirationTimeMilliseconds()
        Expected expiration time in milliseconds or null for none.
      • setExpirationTimeMilliseconds

        public Credential setExpirationTimeMilliseconds​(java.lang.Long expirationTimeMilliseconds)
        Sets the expected expiration time in milliseconds or null for 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) or null if unknown.
      • setExpiresInSeconds

        public Credential setExpiresInSeconds​(java.lang.Long expiresIn)
        Sets the lifetime in seconds of the access token (for example 3600 for an hour) or null 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) or null for none
      • getClientAuthentication

        public final com.google.api.client.http.HttpExecuteInterceptor getClientAuthentication()
        Returns the client authentication or null 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 or null for none.
      • setFromTokenResponse

        public Credential setFromTokenResponse​(TokenResponse tokenResponse)
        Sets the access token, refresh token (if available), and expires-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
      • getRefreshListeners

        public final java.util.Collection<CredentialRefreshListener> getRefreshListeners()
        Returns the unmodifiable collection of listeners for refresh token results.