Package com.google.auth.oauth2
Class ImpersonatedCredentials
- java.lang.Object
-
- com.google.auth.Credentials
-
- com.google.auth.oauth2.OAuth2Credentials
-
- com.google.auth.oauth2.GoogleCredentials
-
- com.google.auth.oauth2.ImpersonatedCredentials
-
- All Implemented Interfaces:
IdTokenProvider
,QuotaProjectIdProvider
,ServiceAccountSigner
,java.io.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:
- Serialized Form
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
ImpersonatedCredentials.Builder
-
Nested classes/interfaces inherited from class com.google.auth.oauth2.OAuth2Credentials
OAuth2Credentials.AsyncRefreshResult, OAuth2Credentials.CacheState, OAuth2Credentials.CredentialsChangedListener, OAuth2Credentials.FutureCallbackToMetadataCallbackAdapter, OAuth2Credentials.OAuthValue, OAuth2Credentials.RefreshTask, OAuth2Credentials.RefreshTaskListener
-
Nested classes/interfaces inherited from interface com.google.auth.oauth2.IdTokenProvider
IdTokenProvider.Option
-
Nested classes/interfaces inherited from interface com.google.auth.ServiceAccountSigner
ServiceAccountSigner.SigningException
-
-
Field Summary
Fields Modifier and Type Field Description private java.util.Calendar
calendar
private static java.lang.String
CLOUD_PLATFORM_SCOPE
private static int
DEFAULT_LIFETIME_IN_SECONDS
private java.util.List<java.lang.String>
delegates
private java.lang.String
iamEndpointOverride
(package private) static java.lang.String
IMPERSONATED_CREDENTIALS_FILE_TYPE
private int
lifetime
private static java.lang.String
RFC3339
private java.util.List<java.lang.String>
scopes
private static long
serialVersionUID
private GoogleCredentials
sourceCredentials
private java.lang.String
targetPrincipal
private HttpTransportFactory
transportFactory
private java.lang.String
transportFactoryClassName
private static int
TWELVE_HOURS_IN_SECONDS
-
Fields inherited from class com.google.auth.oauth2.GoogleCredentials
GDCH_SERVICE_ACCOUNT_FILE_TYPE, QUOTA_PROJECT_ID_HEADER_KEY, quotaProjectId, SERVICE_ACCOUNT_FILE_TYPE, USER_FILE_TYPE
-
Fields inherited from class com.google.auth.oauth2.OAuth2Credentials
clock, DEFAULT_EXPIRATION_MARGIN, DEFAULT_REFRESH_MARGIN, lock, refreshTask
-
Fields inherited from class com.google.auth.Credentials
GOOGLE_DEFAULT_UNIVERSE
-
-
Constructor Summary
Constructors Modifier Constructor Description private
ImpersonatedCredentials(ImpersonatedCredentials.Builder builder)
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description static ImpersonatedCredentials
create(GoogleCredentials sourceCredentials, java.lang.String targetPrincipal, java.util.List<java.lang.String> delegates, java.util.List<java.lang.String> scopes, int lifetime)
static ImpersonatedCredentials
create(GoogleCredentials sourceCredentials, java.lang.String targetPrincipal, java.util.List<java.lang.String> delegates, java.util.List<java.lang.String> scopes, int lifetime, HttpTransportFactory transportFactory)
static ImpersonatedCredentials
create(GoogleCredentials sourceCredentials, java.lang.String targetPrincipal, java.util.List<java.lang.String> delegates, java.util.List<java.lang.String> scopes, int lifetime, HttpTransportFactory transportFactory, java.lang.String quotaProjectId)
static ImpersonatedCredentials
create(GoogleCredentials sourceCredentials, java.lang.String targetPrincipal, java.util.List<java.lang.String> delegates, java.util.List<java.lang.String> scopes, int lifetime, HttpTransportFactory transportFactory, java.lang.String quotaProjectId, java.lang.String iamEndpointOverride)
GoogleCredentials
createScoped(java.util.Collection<java.lang.String> scopes)
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.boolean
createScopedRequired()
Indicates whether the credentials require scopes to be specified via a call toGoogleCredentials.createScoped(java.util.Collection<java.lang.String>)
before use.ImpersonatedCredentials
createWithCustomCalendar(java.util.Calendar calendar)
Clones the impersonated credentials with a new calendar.boolean
equals(java.lang.Object obj)
(package private) static java.lang.String
extractTargetPrincipal(java.lang.String serviceAccountImpersonationUrl)
(package private) static ImpersonatedCredentials
fromJson(java.util.Map<java.lang.String,java.lang.Object> json, HttpTransportFactory transportFactory)
Returns impersonation account credentials defined by JSON using the format generated by gCloud.java.lang.String
getAccount()
Returns the email field of the serviceAccount that is being impersonated.(package private) java.util.List<java.lang.String>
getDelegates()
(package private) java.lang.String
getIamEndpointOverride()
(package private) int
getLifetime()
CredentialTypeForMetrics
getMetricsCredentialType()
Gets the credential type used for internal metrics header.(package private) java.util.List<java.lang.String>
getScopes()
GoogleCredentials
getSourceCredentials()
java.lang.String
getUniverseDomain()
Gets the universe domain for the credential.int
hashCode()
IdToken
idTokenWithAudience(java.lang.String targetAudience, java.util.List<IdTokenProvider.Option> options)
Returns an IdToken for the current Credential.static ImpersonatedCredentials.Builder
newBuilder()
private void
readObject(java.io.ObjectInputStream input)
AccessToken
refreshAccessToken()
Method to refresh the access token according to the specific type of credentials.void
setTransportFactory(HttpTransportFactory httpTransportFactory)
byte[]
sign(byte[] toSign)
Signs the provided bytes using the private key associated with the impersonated service accountImpersonatedCredentials.Builder
toBuilder()
java.lang.String
toString()
-
Methods inherited from class com.google.auth.oauth2.GoogleCredentials
addQuotaProjectIdToRequestMetadata, create, create, createDelegated, createScoped, createScoped, createWithCustomRetryStrategy, createWithQuotaProject, fromStream, fromStream, getAdditionalHeaders, getApplicationDefault, getApplicationDefault, getQuotaProjectId, isDefaultUniverseDomain, isExplicitUniverseDomain, toStringHelper
-
Methods inherited from class com.google.auth.oauth2.OAuth2Credentials
addChangeListener, getAccessToken, getAuthenticationType, getExpirationMargin, getFromServiceLoader, getRefreshMargin, getRequestMetadata, getRequestMetadata, getRequestMetadataInternal, hasRequestMetadata, hasRequestMetadataOnly, newInstance, refresh, refreshIfExpired, removeChangeListener
-
Methods inherited from class com.google.auth.Credentials
blockingGetToCallback, getRequestMetadata
-
-
-
-
Field Detail
-
IMPERSONATED_CREDENTIALS_FILE_TYPE
static final java.lang.String IMPERSONATED_CREDENTIALS_FILE_TYPE
- See Also:
- Constant Field Values
-
serialVersionUID
private static final long serialVersionUID
- See Also:
- Constant Field Values
-
RFC3339
private static final java.lang.String RFC3339
- See Also:
- Constant Field Values
-
TWELVE_HOURS_IN_SECONDS
private static final int TWELVE_HOURS_IN_SECONDS
- See Also:
- Constant Field Values
-
DEFAULT_LIFETIME_IN_SECONDS
private static final int DEFAULT_LIFETIME_IN_SECONDS
- See Also:
- Constant Field Values
-
CLOUD_PLATFORM_SCOPE
private static final java.lang.String CLOUD_PLATFORM_SCOPE
- See Also:
- Constant Field Values
-
sourceCredentials
private GoogleCredentials sourceCredentials
-
targetPrincipal
private java.lang.String targetPrincipal
-
delegates
private java.util.List<java.lang.String> delegates
-
scopes
private java.util.List<java.lang.String> scopes
-
lifetime
private int lifetime
-
iamEndpointOverride
private java.lang.String iamEndpointOverride
-
transportFactoryClassName
private final java.lang.String transportFactoryClassName
-
transportFactory
private transient HttpTransportFactory transportFactory
-
calendar
private transient java.util.Calendar calendar
-
-
Constructor Detail
-
ImpersonatedCredentials
private ImpersonatedCredentials(ImpersonatedCredentials.Builder builder) throws java.io.IOException
- Throws:
java.io.IOException
-
-
Method Detail
-
create
public static ImpersonatedCredentials create(GoogleCredentials sourceCredentials, java.lang.String targetPrincipal, java.util.List<java.lang.String> delegates, java.util.List<java.lang.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 impersonatedelegates
- 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 grantlifetime
- 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, java.lang.String targetPrincipal, java.util.List<java.lang.String> delegates, java.util.List<java.lang.String> scopes, int lifetime, HttpTransportFactory transportFactory, java.lang.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 impersonatedelegates
- 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 grantlifetime
- 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, java.lang.String targetPrincipal, java.util.List<java.lang.String> delegates, java.util.List<java.lang.String> scopes, int lifetime, HttpTransportFactory transportFactory, java.lang.String quotaProjectId, java.lang.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 impersonatedelegates
- 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 grantlifetime
- 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, java.lang.String targetPrincipal, java.util.List<java.lang.String> delegates, java.util.List<java.lang.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 impersonatedelegates
- 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 grantlifetime
- 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
-
extractTargetPrincipal
static java.lang.String extractTargetPrincipal(java.lang.String serviceAccountImpersonationUrl)
-
getAccount
public java.lang.String getAccount()
Returns the email field of the serviceAccount that is being impersonated.- Specified by:
getAccount
in interfaceServiceAccountSigner
- Returns:
- email address of the impersonated service account
-
getIamEndpointOverride
java.lang.String getIamEndpointOverride()
-
getDelegates
java.util.List<java.lang.String> getDelegates()
-
getScopes
java.util.List<java.lang.String> getScopes()
-
getSourceCredentials
public GoogleCredentials getSourceCredentials()
-
getLifetime
int getLifetime()
-
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 interfaceServiceAccountSigner
- Parameters:
toSign
- bytes to sign- Returns:
- signed bytes
- Throws:
ServiceAccountSigner.SigningException
- if the attempt to sign the provided bytes failed- See Also:
- Blob Signing
-
fromJson
static ImpersonatedCredentials fromJson(java.util.Map<java.lang.String,java.lang.Object> json, HttpTransportFactory transportFactory) throws java.io.IOException
Returns impersonation account credentials defined by JSON using the format generated by gCloud. The source credentials in the JSON should be either user account credentials or service account credentials.- Parameters:
json
- a map from the JSON representing the credentialstransportFactory
- HTTP transport factory, creates the transport used to get access tokens- Returns:
- the credentials defined by the JSON
- Throws:
java.io.IOException
- if the credential cannot be created from the JSON.
-
createScopedRequired
public boolean createScopedRequired()
Description copied from class:GoogleCredentials
Indicates whether the credentials require scopes to be specified via a call toGoogleCredentials.createScoped(java.util.Collection<java.lang.String>)
before use.- Overrides:
createScopedRequired
in classGoogleCredentials
- Returns:
- Whether the credentials require scopes to be specified.
-
createScoped
public GoogleCredentials createScoped(java.util.Collection<java.lang.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 classGoogleCredentials
- Parameters:
scopes
- Collection of scopes to request.- Returns:
- GoogleCredentials with requested scopes.
-
getMetricsCredentialType
public CredentialTypeForMetrics getMetricsCredentialType()
Description copied from class:Credentials
Gets the credential type used for internal metrics header.The default is
CredentialTypeForMetrics.DO_NOT_SEND
. For a credential that is established to track for metrics, this default should be overridden.- Overrides:
getMetricsCredentialType
in classCredentials
- Returns:
- a enum value for credential type
-
createWithCustomCalendar
public ImpersonatedCredentials createWithCustomCalendar(java.util.Calendar calendar)
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 java.lang.String getUniverseDomain() throws java.io.IOException
Gets the universe domain for the credential.- Overrides:
getUniverseDomain
in classGoogleCredentials
- Returns:
- the universe domain from source credentials
- Throws:
java.io.IOException
- extending classes might have to do remote calls to determine the universe domain. The exception must implementRetryable
andisRetryable()
will return true if the operation may be retried.
-
refreshAccessToken
public AccessToken refreshAccessToken() throws java.io.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 classOAuth2Credentials
- Returns:
- never
- Throws:
java.io.IOException
-
idTokenWithAudience
public IdToken idTokenWithAudience(java.lang.String targetAudience, java.util.List<IdTokenProvider.Option> options) throws java.io.IOException
Returns an IdToken for the current Credential.- Specified by:
idTokenWithAudience
in interfaceIdTokenProvider
- Parameters:
targetAudience
- the audience field for the issued ID tokenoptions
- 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:
java.io.IOException
- if the attempt to get an ID token failed
-
hashCode
public int hashCode()
- Overrides:
hashCode
in classGoogleCredentials
-
toString
public java.lang.String toString()
- Overrides:
toString
in classGoogleCredentials
-
equals
public boolean equals(java.lang.Object obj)
- Overrides:
equals
in classGoogleCredentials
-
toBuilder
public ImpersonatedCredentials.Builder toBuilder()
- Overrides:
toBuilder
in classGoogleCredentials
-
newBuilder
public static ImpersonatedCredentials.Builder newBuilder()
-
readObject
private void readObject(java.io.ObjectInputStream input) throws java.io.IOException, java.lang.ClassNotFoundException
- Throws:
java.io.IOException
java.lang.ClassNotFoundException
-
-