com.google.api.client.googleapis.auth.oauth2
Class GoogleCredential

java.lang.Object
  extended by com.google.api.client.auth.oauth2.Credential
      extended by com.google.api.client.googleapis.auth.oauth2.GoogleCredential
All Implemented Interfaces:
HttpExecuteInterceptor, HttpRequestInitializer, HttpUnsuccessfulResponseHandler

public class GoogleCredential
extends Credential

Thread-safe Google-specific implementation of the 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.

There are three modes supported: access token only, refresh token flow, and service account flow (with or without impersonating a user).

If all you have is an access token, you simply pass the TokenResponse to the credential using Credential.setFromTokenResponse(TokenResponse). Google credential uses BearerToken.authorizationHeaderAccessMethod() as the access method. Sample usage:

  public static GoogleCredential createCredentialWithAccessTokenOnly(
      HttpTransport transport, JsonFactory jsonFactory, TokenResponse tokenResponse) {
    return new GoogleCredential().setFromTokenResponse(tokenResponse);
  }
 

If you have a refresh token, it is similar to the case of access token only, but you additionally need to pass the credential the client secrets using GoogleCredential.Builder.setClientSecrets(GoogleClientSecrets) or GoogleCredential.Builder.setClientSecrets(String, String). Google credential uses GoogleOAuthConstants.TOKEN_SERVER_URL as the token server URL, and ClientParametersAuthentication with the client ID and secret as the client authentication. Sample usage:

  public static GoogleCredential createCredentialWithRefreshToken(HttpTransport transport,
      JsonFactory jsonFactory, GoogleClientSecrets clientSecrets, TokenResponse tokenResponse) {
    return new GoogleCredential.Builder().setTransport(transport)
        .setJsonFactory(jsonFactory)
        .setClientSecrets(clientSecrets)
        .build()
        .setFromTokenResponse(tokenResponse);
  }
 

The service account flow is used when you want to access data owned by your client application. You download the private key in a .p12 file from the Google APIs Console. Use GoogleCredential.Builder.setServiceAccountId(String), GoogleCredential.Builder.setServiceAccountPrivateKeyFromP12File(File), and GoogleCredential.Builder.setServiceAccountScopes(String...). Sample usage:

  public static GoogleCredential createCredentialForServiceAccount(
      HttpTransport transport,
      JsonFactory jsonFactory,
      String serviceAccountId,
      Iterable<String> serviceAccountScopes,
      File p12File) throws GeneralSecurityException, IOException {
    return new GoogleCredential.Builder().setTransport(transport)
        .setJsonFactory(jsonFactory)
        .setServiceAccountId(serviceAccountId)
        .setServiceAccountScopes(serviceAccountScopes)
        .setServiceAccountPrivateKeyFromP12File(p12File)
        .build();
  }
 

You can also use the service account flow to impersonate a user in a domain that you own. This is very similar to the service account flow above, but you additionally call GoogleCredential.Builder.setServiceAccountUser(String). Sample usage:

  public static GoogleCredential createCredentialForServiceAccountImpersonateUser(
      HttpTransport transport,
      JsonFactory jsonFactory,
      String serviceAccountId,
      Iterable<String> serviceAccountScopes,
      File p12File,
      String serviceAccountUser) throws GeneralSecurityException, IOException {
    return new GoogleCredential.Builder().setTransport(transport)
        .setJsonFactory(jsonFactory)
        .setServiceAccountId(serviceAccountId)
        .setServiceAccountScopes(serviceAccountScopes)
        .setServiceAccountPrivateKeyFromP12File(p12File)
        .setServiceAccountUser(serviceAccountUser)
        .build();
  }
 

If you need to persist the access token in a data store, use CredentialStore and GoogleCredential.Builder.addRefreshListener(CredentialRefreshListener).

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
Author:
Yaniv Inbar

Nested Class Summary
static class GoogleCredential.Builder
          Google credential builder.
 
Nested classes/interfaces inherited from class com.google.api.client.auth.oauth2.Credential
Credential.AccessMethod
 
Constructor Summary
  GoogleCredential()
          Constructor with the ability to access protected resources, but not refresh tokens.
protected GoogleCredential(Credential.AccessMethod method, HttpTransport transport, JsonFactory jsonFactory, String tokenServerEncodedUrl, HttpExecuteInterceptor clientAuthentication, HttpRequestInitializer requestInitializer, List<CredentialRefreshListener> refreshListeners, String serviceAccountId, String serviceAccountScopes, PrivateKey serviceAccountPrivateKey, String serviceAccountUser)
           
protected GoogleCredential(Credential.AccessMethod method, HttpTransport transport, JsonFactory jsonFactory, String tokenServerEncodedUrl, HttpExecuteInterceptor clientAuthentication, HttpRequestInitializer requestInitializer, List<CredentialRefreshListener> refreshListeners, String serviceAccountId, String serviceAccountScopes, PrivateKey serviceAccountPrivateKey, String serviceAccountUser, Clock clock)
           
 
Method Summary
protected  TokenResponse executeRefreshToken()
           
 String getServiceAccountId()
          Returns the service account ID (typically an e-mail address) or null if not using the service account flow.
 PrivateKey getServiceAccountPrivateKey()
          Returns the private key to use with the the service account flow or null if not using the service account flow.
 String getServiceAccountScopes()
          Returns the space-separated OAuth scopes to use with the the service account flow or null if not using the service account flow.
 String getServiceAccountUser()
          Returns the email address of the user the application is trying to impersonate in the service account flow or null for none or if not using the service account flow.
 GoogleCredential setAccessToken(String accessToken)
           
 GoogleCredential setExpirationTimeMilliseconds(Long expirationTimeMilliseconds)
           
 GoogleCredential setExpiresInSeconds(Long expiresIn)
           
 GoogleCredential setFromTokenResponse(TokenResponse tokenResponse)
           
 GoogleCredential setRefreshToken(String refreshToken)
           
 
Methods inherited from class com.google.api.client.auth.oauth2.Credential
getAccessToken, getClientAuthentication, getClock, getExpirationTimeMilliseconds, getExpiresInSeconds, getJsonFactory, getMethod, getRefreshListeners, getRefreshToken, getRequestInitializer, getTokenServerEncodedUrl, getTransport, handleResponse, initialize, intercept, refreshToken
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

GoogleCredential

public GoogleCredential()
Constructor with the ability to access protected resources, but not refresh tokens.

To use with the ability to refresh tokens, use GoogleCredential.Builder.


GoogleCredential

protected GoogleCredential(Credential.AccessMethod method,
                           HttpTransport transport,
                           JsonFactory jsonFactory,
                           String tokenServerEncodedUrl,
                           HttpExecuteInterceptor clientAuthentication,
                           HttpRequestInitializer requestInitializer,
                           List<CredentialRefreshListener> refreshListeners,
                           String serviceAccountId,
                           String serviceAccountScopes,
                           PrivateKey serviceAccountPrivateKey,
                           String serviceAccountUser)
Parameters:
method - method of presenting the access token to the resource server (for example BearerToken.authorizationHeaderAccessMethod())
transport - HTTP transport for executing refresh token request or null if not refreshing tokens
jsonFactory - JSON factory to use for parsing response for refresh token request or null if not refreshing tokens
tokenServerEncodedUrl - encoded token server URL or null if not refreshing tokens
clientAuthentication - client authentication or null for none (see TokenRequest.setClientAuthentication(HttpExecuteInterceptor))
requestInitializer - HTTP request initializer for refresh token requests to the token server or null for none.
refreshListeners - listeners for refresh token results or null for none
serviceAccountId - service account ID (typically an e-mail address) or null if not using the service account flow
serviceAccountScopes - space-separated OAuth scopes to use with the the service account flow or null if not using the service account flow
serviceAccountPrivateKey - private key to use with the the service account flow or null if not using the service account flow
serviceAccountUser - email address of the user the application is trying to impersonate in the service account flow or null for none or if not using the service account flow

GoogleCredential

protected GoogleCredential(Credential.AccessMethod method,
                           HttpTransport transport,
                           JsonFactory jsonFactory,
                           String tokenServerEncodedUrl,
                           HttpExecuteInterceptor clientAuthentication,
                           HttpRequestInitializer requestInitializer,
                           List<CredentialRefreshListener> refreshListeners,
                           String serviceAccountId,
                           String serviceAccountScopes,
                           PrivateKey serviceAccountPrivateKey,
                           String serviceAccountUser,
                           Clock clock)
Parameters:
method - method of presenting the access token to the resource server (for example BearerToken.authorizationHeaderAccessMethod())
transport - HTTP transport for executing refresh token request or null if not refreshing tokens
jsonFactory - JSON factory to use for parsing response for refresh token request or null if not refreshing tokens
tokenServerEncodedUrl - encoded token server URL or null if not refreshing tokens
clientAuthentication - client authentication or null for none (see TokenRequest.setClientAuthentication(HttpExecuteInterceptor))
requestInitializer - HTTP request initializer for refresh token requests to the token server or null for none.
refreshListeners - listeners for refresh token results or null for none
serviceAccountId - service account ID (typically an e-mail address) or null if not using the service account flow
serviceAccountScopes - space-separated OAuth scopes to use with the the service account flow or null if not using the service account flow
serviceAccountPrivateKey - private key to use with the the service account flow or null if not using the service account flow
serviceAccountUser - email address of the user the application is trying to impersonate in the service account flow or null for none or if not using the service account flow
clock - The clock to use for expiration check
Since:
1.9
Method Detail

setAccessToken

public GoogleCredential setAccessToken(String accessToken)
Overrides:
setAccessToken in class Credential

setRefreshToken

public GoogleCredential setRefreshToken(String refreshToken)
Overrides:
setRefreshToken in class Credential

setExpirationTimeMilliseconds

public GoogleCredential setExpirationTimeMilliseconds(Long expirationTimeMilliseconds)
Overrides:
setExpirationTimeMilliseconds in class Credential

setExpiresInSeconds

public GoogleCredential setExpiresInSeconds(Long expiresIn)
Overrides:
setExpiresInSeconds in class Credential

setFromTokenResponse

public GoogleCredential setFromTokenResponse(TokenResponse tokenResponse)
Overrides:
setFromTokenResponse in class Credential

executeRefreshToken

protected TokenResponse executeRefreshToken()
                                     throws IOException
Overrides:
executeRefreshToken in class Credential
Throws:
IOException

getServiceAccountId

public final String getServiceAccountId()
Returns the service account ID (typically an e-mail address) or null if not using the service account flow.


getServiceAccountScopes

public final String getServiceAccountScopes()
Returns the space-separated OAuth scopes to use with the the service account flow or null if not using the service account flow.


getServiceAccountPrivateKey

public final PrivateKey getServiceAccountPrivateKey()
Returns the private key to use with the the service account flow or null if not using the service account flow.


getServiceAccountUser

public final String getServiceAccountUser()
Returns the email address of the user the application is trying to impersonate in the service account flow or null for none or if not using the service account flow.



Copyright © 2010-2012 Google. All Rights Reserved.