Class ImpersonatedCredentials

All Implemented Interfaces:
IdTokenProvider, QuotaProjectIdProvider, ServiceAccountSigner, Serializable

public class ImpersonatedCredentials extends GoogleCredentials implements ServiceAccountSigner, IdTokenProvider
ImpersonatedCredentials allowing credentials issued to a user or service account to impersonate another. The source project using ImpersonatedCredentials must enable the "IAMCredentials" API. Also, the target service account must grant the originating principal the "Service Account Token Creator" IAM role.

Usage:

 String credPath = "/path/to/svc_account.json";
 ServiceAccountCredentials sourceCredentials = ServiceAccountCredentials
     .fromStream(new FileInputStream(credPath));
 sourceCredentials = (ServiceAccountCredentials) sourceCredentials
     .createScoped(Arrays.asList("https://www.googleapis.com/auth/iam"));

 ImpersonatedCredentials targetCredentials = ImpersonatedCredentials.create(sourceCredentials,
     "impersonated-account@project.iam.gserviceaccount.com", null,
     Arrays.asList("https://www.googleapis.com/auth/devstorage.read_only"), 300);

 Storage storage_service = StorageOptions.newBuilder().setProjectId("project-id")
    .setCredentials(targetCredentials).build().getService();

 for (Bucket b : storage_service.list().iterateAll())
     System.out.println(b);
 
See Also:
  • Method Details

    • create

      public static ImpersonatedCredentials create(GoogleCredentials sourceCredentials, String targetPrincipal, List<String> delegates, List<String> scopes, int lifetime, HttpTransportFactory transportFactory)
      Parameters:
      sourceCredentials - the source credential used to acquire the impersonated credentials. It should be either a user account credential or a service account credential.
      targetPrincipal - the service account to impersonate
      delegates - the chained list of delegates required to grant the final access_token. If set, the sequence of identities must have "Service Account Token Creator" capability granted to the preceding identity. For example, if set to [serviceAccountB, serviceAccountC], the sourceCredential must have the Token Creator role on serviceAccountB. serviceAccountB must have the Token Creator on serviceAccountC. Finally, C must have Token Creator on target_principal. If unset, sourceCredential must have that role on targetPrincipal.
      scopes - scopes to request during the authorization grant
      lifetime - number of seconds the delegated credential should be valid. By default this value should be at most 3600. However, you can follow these instructions to set up the service account and extend the maximum lifetime to 43200 (12 hours). If the given lifetime is 0, default value 3600 will be used instead when creating the credentials.
      transportFactory - HTTP transport factory that creates the transport used to get access tokens
      Returns:
      new credentials
    • create

      public static ImpersonatedCredentials create(GoogleCredentials sourceCredentials, String targetPrincipal, List<String> delegates, List<String> scopes, int lifetime, HttpTransportFactory transportFactory, String quotaProjectId)
      Parameters:
      sourceCredentials - the source credential used to acquire the impersonated credentials. It should be either a user account credential or a service account credential.
      targetPrincipal - the service account to impersonate
      delegates - the chained list of delegates required to grant the final access_token. If set, the sequence of identities must have "Service Account Token Creator" capability granted to the preceding identity. For example, if set to [serviceAccountB, serviceAccountC], the sourceCredential must have the Token Creator role on serviceAccountB. serviceAccountB must have the Token Creator on serviceAccountC. Finally, C must have Token Creator on target_principal. If unset, sourceCredential must have that role on targetPrincipal.
      scopes - scopes to request during the authorization grant
      lifetime - number of seconds the delegated credential should be valid. By default this value should be at most 3600. However, you can follow these instructions to set up the service account and extend the maximum lifetime to 43200 (12 hours). If the given lifetime is 0, default value 3600 will be used instead when creating the credentials.
      transportFactory - HTTP transport factory that creates the transport used to get access tokens.
      quotaProjectId - the project used for quota and billing purposes. Should be null unless the caller wants to use a project different from the one that owns the impersonated credential for billing/quota purposes.
      Returns:
      new credentials
    • create

      public static ImpersonatedCredentials create(GoogleCredentials sourceCredentials, String targetPrincipal, List<String> delegates, List<String> scopes, int lifetime, HttpTransportFactory transportFactory, String quotaProjectId, String iamEndpointOverride)
      Parameters:
      sourceCredentials - the source credential used to acquire the impersonated credentials. It should be either a user account credential or a service account credential.
      targetPrincipal - the service account to impersonate
      delegates - the chained list of delegates required to grant the final access_token. If set, the sequence of identities must have "Service Account Token Creator" capability granted to the preceding identity. For example, if set to [serviceAccountB, serviceAccountC], the sourceCredential must have the Token Creator role on serviceAccountB. serviceAccountB must have the Token Creator on serviceAccountC. Finally, C must have Token Creator on target_principal. If unset, sourceCredential must have that role on targetPrincipal.
      scopes - scopes to request during the authorization grant
      lifetime - number of seconds the delegated credential should be valid. By default this value should be at most 3600. However, you can follow these instructions to set up the service account and extend the maximum lifetime to 43200 (12 hours). If the given lifetime is 0, default value 3600 will be used instead when creating the credentials.
      transportFactory - HTTP transport factory that creates the transport used to get access tokens.
      quotaProjectId - the project used for quota and billing purposes. Should be null unless the caller wants to use a project different from the one that owns the impersonated credential for billing/quota purposes.
      iamEndpointOverride - The full IAM endpoint override with the target_principal embedded. This is useful when supporting impersonation with regional endpoints.
      Returns:
      new credentials
    • create

      public static ImpersonatedCredentials create(GoogleCredentials sourceCredentials, String targetPrincipal, List<String> delegates, List<String> scopes, int lifetime)
      Parameters:
      sourceCredentials - the source credential used to acquire the impersonated credentials. It should be either a user account credential or a service account credential.
      targetPrincipal - the service account to impersonate
      delegates - the chained list of delegates required to grant the final access_token. If set, the sequence of identities must have "Service Account Token Creator" capability granted to the preceding identity. For example, if set to [serviceAccountB, serviceAccountC], the sourceCredential must have the Token Creator role on serviceAccountB. serviceAccountB must have the Token Creator on serviceAccountC. Finally, C must have Token Creator on target_principal. If left unset, sourceCredential must have that role on targetPrincipal.
      scopes - scopes to request during the authorization grant
      lifetime - number of seconds the delegated credential should be valid. By default this value should be at most 3600. However, you can follow these instructions to set up the service account and extend the maximum lifetime to 43200 (12 hours). https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth If the given lifetime is 0, default value 3600 will be used instead when creating the credentials.
      Returns:
      new credentials
    • getAccount

      public String getAccount()
      Returns the email field of the serviceAccount that is being impersonated.
      Specified by:
      getAccount in interface ServiceAccountSigner
      Returns:
      email address of the impersonated service account
    • getSourceCredentials

      public GoogleCredentials getSourceCredentials()
    • setTransportFactory

      public void setTransportFactory(HttpTransportFactory httpTransportFactory)
    • sign

      public byte[] sign(byte[] toSign)
      Signs the provided bytes using the private key associated with the impersonated service account
      Specified by:
      sign in interface ServiceAccountSigner
      Parameters:
      toSign - bytes to sign
      Returns:
      signed bytes
      Throws:
      ServiceAccountSigner.SigningException - if the attempt to sign the provided bytes failed
      See Also:
    • fromStream

      public static ImpersonatedCredentials fromStream(InputStream credentialsStream) throws IOException
      Returns credentials defined by a ImpersonatedCredential key file in JSON format from the Google Developers Console.

      Important: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud Platform, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to .

      Parameters:
      credentialsStream - the stream with the credential definition.
      Returns:
      the credential defined by the credentialsStream.
      Throws:
      IOException - if the credential cannot be created from the stream.
    • fromStream

      public static ImpersonatedCredentials fromStream(InputStream credentialsStream, HttpTransportFactory transportFactory) throws IOException
      Returns credentials defined by a ImpersonatedCredential key file in JSON format from the Google Developers Console.

      Important: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud Platform, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to .

      Parameters:
      credentialsStream - the stream with the credential definition.
      transportFactory - HTTP transport factory, creates the transport used to get access tokens.
      Returns:
      the credential defined by the credentialsStream.
      Throws:
      IOException - if the credential cannot be created from the stream.
    • createScopedRequired

      public boolean createScopedRequired()
      Description copied from class: GoogleCredentials
      Indicates whether the credentials require scopes to be specified via a call to GoogleCredentials.createScoped(java.util.Collection<java.lang.String>) before use.
      Overrides:
      createScopedRequired in class GoogleCredentials
      Returns:
      Whether the credentials require scopes to be specified.
    • createScoped

      public GoogleCredentials createScoped(Collection<String> scopes)
      Description copied from class: GoogleCredentials
      If the credentials support scopes, creates a copy of the identity with the specified scopes, invalidates the existing scoped access token; otherwise, return the same instance.
      Overrides:
      createScoped in class GoogleCredentials
      Parameters:
      scopes - Collection of scopes to request.
      Returns:
      GoogleCredentials with requested scopes.
    • getMetricsCredentialType

      public CredentialTypeForMetrics getMetricsCredentialType()
      Overrides:
      getMetricsCredentialType in class Credentials
    • createWithCustomCalendar

      @ObsoleteApi("This method is obsolete and will be removed in a future release.") public ImpersonatedCredentials createWithCustomCalendar(Calendar calendar)
      This method is marked obsolete. There is no alternative to setting a custom calendar for the Credential.

      Clones the impersonated credentials with a new calendar.

      Parameters:
      calendar - the calendar that will be used by the new ImpersonatedCredentials instance when parsing the received expiration time of the refreshed access token
      Returns:
      the cloned impersonated credentials with the given custom calendar
    • getUniverseDomain

      public String getUniverseDomain() throws IOException
      Gets the universe domain for the credential.
      Overrides:
      getUniverseDomain in class GoogleCredentials
      Returns:
      the universe domain from source credentials
      Throws:
      IOException
    • refreshAccessToken

      public AccessToken refreshAccessToken() throws IOException
      Description copied from class: OAuth2Credentials
      Method to refresh the access token according to the specific type of credentials.

      Throws IllegalStateException if not overridden since direct use of OAuth2Credentials is only for temporary or non-refreshing access tokens.

      Overrides:
      refreshAccessToken in class OAuth2Credentials
      Returns:
      never
      Throws:
      IOException
    • idTokenWithAudience

      public IdToken idTokenWithAudience(String targetAudience, List<IdTokenProvider.Option> options) throws IOException
      Returns an IdToken for the current Credential.
      Specified by:
      idTokenWithAudience in interface IdTokenProvider
      Parameters:
      targetAudience - the audience field for the issued ID token
      options - credential specific options for for the token. For example, an ID token for an ImpersonatedCredentials can return the email address within the token claims if "ImpersonatedCredentials.INCLUDE_EMAIL" is provided as a list option.
      Only one option value is supported: "ImpersonatedCredentials.INCLUDE_EMAIL" If no options are set, the default excludes the "includeEmail" attribute in the API request.
      Returns:
      IdToken object which includes the raw id_token, expiration, and audience
      Throws:
      IOException - if the attempt to get an ID token failed
    • hashCode

      public int hashCode()
      Overrides:
      hashCode in class GoogleCredentials
    • toString

      public String toString()
      Returns a string representation of this credential.

      Security Warning: The output of this method includes the source credentials which may recursively contain sensitive fields such as access tokens. Do not log this output in production environments as it may expose sensitive credentials.

      Overrides:
      toString in class GoogleCredentials
    • equals

      public boolean equals(Object obj)
      Overrides:
      equals in class GoogleCredentials
    • toBuilder

      public ImpersonatedCredentials.Builder toBuilder()
      Overrides:
      toBuilder in class GoogleCredentials
    • newBuilder

      public static ImpersonatedCredentials.Builder newBuilder()