Class GoogleCredential (1.60.0)

public class GoogleCredential : ICredential, IConfigurableHttpClientInitializer, ITokenAccessWithHeaders, ITokenAccess, IOidcTokenProvider, IBlobSigner

Credential for authorizing calls using OAuth 2.0. It is a convenience wrapper that allows handling of different types of credentials (like ServiceAccountCredential, ComputeCredential or UserCredential) in a unified way.

See GetApplicationDefaultAsync(CancellationToken) for the credential retrieval logic.

Inheritance

object > GoogleCredential

Namespace

GoogleApisAuthOAuth2

Assembly

Google.Apis.Auth.dll

Properties

IsCreateScopedRequired

public virtual bool IsCreateScopedRequired { get; }

Returns true only if this credential supports explicit scopes to be set via this library but no explicit scopes have been set. A credential with explicit scopes set may be created by calling CreateScoped(IEnumerable<string>).

For accessing Google services, credentials need to be scoped. Credentials have some default scoping, but this library supports explicit scopes to be set for certain credentials.

  1. ComputeCredential is scoped by default but in some environments it may be scoped explicitly, for instance when running on GKE with Workload Identity or on AppEngine Flex. It's possible to create a ComputeCredential with explicit scopes set by calling CreateScoped(IEnumerable<string>). If running on an environment that does not accept explicit scoping, for instance GCE where scopes are set on the VM, explicit scopes will be ignored.
  2. UserCredential is scoped by default, as scopes were obtained during the consent screen. It's not possible to change the default scopes of a UserCredential.
  3. ServiceAccountCredential is not scoped by default but when used without explicit scopes to access a Google service, the service's default scopes will be assumed. It's possible to create a ServiceAccountCredential with explicit scopes set by calling CreateScoped(IEnumerable<string>)
  4. ImpersonatedCredential is not scoped by default but when used without explicit scopes to access a Google service, the service's default scopes will be assumed. Note that the scopes of an SourceCredential have no bearings on the ImpersonatedCredential scopes. It's possible to create an ImpersonatedCredential with explicit scopes set by calling CreateScoped(IEnumerable<string>)

Property Value
TypeDescription
bool

QuotaProject

public string QuotaProject { get; }

The ID of the project associated to this credential for the purposes of quota calculation and billing. May be null.

Property Value
TypeDescription
string

UnderlyingCredential

public ICredential UnderlyingCredential { get; }

Gets the underlying credential instance being wrapped.

Property Value
TypeDescription
ICredential

Methods

CreateScoped(IEnumerable<string>)

public virtual GoogleCredential CreateScoped(IEnumerable<string> scopes)

If this library supports setting explicit scopes on this credential, this method will creates a copy of the credential with the specified scopes. Otherwise, it returns the same instance. See IsCreateScopedRequired for more information.

Parameter
NameDescription
scopesIEnumerablestring
Returns
TypeDescription
GoogleCredential

CreateScoped(params string[])

public GoogleCredential CreateScoped(params string[] scopes)

If the credential supports scopes, creates a copy with the specified scopes. Otherwise, it returns the same instance.

Parameter
NameDescription
scopesstring
Returns
TypeDescription
GoogleCredential

CreateWithEnvironmentQuotaProject()

public GoogleCredential CreateWithEnvironmentQuotaProject()

Creates a copy of this credential with the ambient quota project as set in QuotaProjectEnvironmentVariable. If QuotaProjectEnvironmentVariable is not set, or if it is set to the empty value, this method returns this instance.

Returns
TypeDescription
GoogleCredential
Remarks

The ADC quota project value will be overwritten only if the environment variable is present and set to a non-empty value. If the environment variable is not present or if it is present but unset, the credential returned will maintain whatever quota project value it already had, i.e. the credential's quota project value will not be unset.

CreateWithHttpClientFactory(IHttpClientFactory)

public virtual GoogleCredential CreateWithHttpClientFactory(IHttpClientFactory factory)

Creates a copy of this credential with the specified HTTP client factory.

Parameter
NameDescription
factoryIHttpClientFactory

The HTTP client factory to be used by the new credential. May be null, in which case the default HttpClientFactory will be used.

Returns
TypeDescription
GoogleCredential

CreateWithQuotaProject(string)

public virtual GoogleCredential CreateWithQuotaProject(string quotaProject)

Creates a copy of this credential with the specified quota project.

Parameter
NameDescription
quotaProjectstring

The quota project to use for the copy. May be null.

Returns
TypeDescription
GoogleCredential

A copy of this credential with QuotaProject set to quotaProject.

CreateWithUser(string)

public virtual GoogleCredential CreateWithUser(string user)

If the credential supports Domain Wide Delegation, this method creates a copy of the credential with the specified user. Otherwise, it throws System.InvalidOperationException. At the moment only ServiceAccountCredential supports Domain Wide Delegation.

Parameter
NameDescription
userstring

The user that the returned credential will be a delegate for.

Returns
TypeDescription
GoogleCredential

A copy of this credential with the user set to user.

Exceptions
TypeDescription
System.InvalidOperationException

When the credential type doesn't support Domain Wide Delegation.

FromAccessToken(string, IAccessMethod)

public static GoogleCredential FromAccessToken(string accessToken, IAccessMethod accessMethod = null)

Create a GoogleCredential directly from the provided access token. The access token will not be automatically refreshed.

Parameters
NameDescription
accessTokenstring

The access token to use within this credential.

accessMethodIAccessMethod

Optional. The IAccessMethod to use within this credential. If null, will default to BearerToken.AuthorizationHeaderAccessMethod.

Returns
TypeDescription
GoogleCredential

A credential based on the provided access token.

FromComputeCredential(ComputeCredential)

public static GoogleCredential FromComputeCredential(ComputeCredential computeCredential = null)

Create a GoogleCredential from a ComputeCredential. In general, do not use this method. Call GetApplicationDefault() or GetApplicationDefaultAsync(CancellationToken), which will provide the most suitable credentials for the current platform.

Parameter
NameDescription
computeCredentialComputeCredential

Optional. The compute credential to use in the returned GoogleCredential. If null, then a new ComputeCredential will be instantiated, using the default ComputeCredential.Initializer.

Returns
TypeDescription
GoogleCredential

A GoogleCredential with an underlying ComputeCredential.

FromFile(string)

public static GoogleCredential FromFile(string path)

Loads credential from the specified file containing JSON credential data.

The file can contain a Service Account key file in JSON format from the Google Developers Console or a stored user credential using the format supported by the Cloud SDK.

Parameter
NameDescription
pathstring

The path to the credential file.

Returns
TypeDescription
GoogleCredential

The loaded credentials.

FromFileAsync(string, CancellationToken)

public static Task<GoogleCredential> FromFileAsync(string path, CancellationToken cancellationToken)

Loads credential from the specified file containing JSON credential data.

The file can contain a Service Account key file in JSON format from the Google Developers Console or a stored user credential using the format supported by the Cloud SDK.

Parameters
NameDescription
pathstring

The path to the credential file.

cancellationTokenCancellationToken

Cancellation token for the operation.

Returns
TypeDescription
TaskGoogleCredential

The loaded credentials.

FromJson(string)

public static GoogleCredential FromJson(string json)

Loads credential from a string containing JSON credential data.

The string can contain a Service Account key file in JSON format from the Google Developers Console or a stored user credential using the format supported by the Cloud SDK.

Parameter
NameDescription
jsonstring
Returns
TypeDescription
GoogleCredential

FromJsonParameters(JsonCredentialParameters)

public static GoogleCredential FromJsonParameters(JsonCredentialParameters credentialParameters)

Loads a credential from JSON credential parameters. Fields are a union of credential fields for all supported types. JsonCredentialParameters for more detailed information about supported types and corresponding fields.

Parameter
NameDescription
credentialParametersJsonCredentialParameters
Returns
TypeDescription
GoogleCredential

FromServiceAccountCredential(ServiceAccountCredential)

public static GoogleCredential FromServiceAccountCredential(ServiceAccountCredential credential)

Creates a GoogleCredential wrapping a ServiceAccountCredential.

Parameter
NameDescription
credentialServiceAccountCredential
Returns
TypeDescription
GoogleCredential

FromStream(Stream)

public static GoogleCredential FromStream(Stream stream)

Loads credential from stream containing JSON credential data.

The stream can contain a Service Account key file in JSON format from the Google Developers Console or a stored user credential using the format supported by the Cloud SDK.

Parameter
NameDescription
streamStream
Returns
TypeDescription
GoogleCredential

FromStreamAsync(Stream, CancellationToken)

public static Task<GoogleCredential> FromStreamAsync(Stream stream, CancellationToken cancellationToken)

Loads credential from stream containing JSON credential data.

The stream can contain a Service Account key file in JSON format from the Google Developers Console or a stored user credential using the format supported by the Cloud SDK.

Parameters
NameDescription
streamStream
cancellationTokenCancellationToken
Returns
TypeDescription
TaskGoogleCredential

GetApplicationDefault()

public static GoogleCredential GetApplicationDefault()

Synchronously returns the Application Default Credentials which are ambient credentials that identify and authorize the whole application. See GetApplicationDefaultAsync(CancellationToken) for details on application default credentials.

This method will block until the credentials are available (or an exception is thrown). It is highly preferable to call GetApplicationDefaultAsync(CancellationToken) where possible.

Returns
TypeDescription
GoogleCredential

The application default credentials.

GetApplicationDefaultAsync()

public static Task<GoogleCredential> GetApplicationDefaultAsync()

Returns the Application Default Credentials which are ambient credentials that identify and authorize the whole application. See GetApplicationDefaultAsync(CancellationToken) for more details.

Returns
TypeDescription
TaskGoogleCredential

A task which completes with the application default credentials.

GetApplicationDefaultAsync(CancellationToken)

public static Task<GoogleCredential> GetApplicationDefaultAsync(CancellationToken cancellationToken)

Returns the Application Default Credentials which are ambient credentials that identify and authorize the whole application.

The ambient credentials are determined as following order:

  1. The environment variable GOOGLE_APPLICATION_CREDENTIALS is checked. If this variable is specified, it should point to a file that defines the credentials. The simplest way to get a credential for this purpose is to create a service account using the Google Developers Console in the section APIs & Auth, in the sub-section Credentials. Create a service account or choose an existing one and select Generate new JSON key. Set the environment variable to the path of the JSON file downloaded.
  2. If you have installed the Google Cloud SDK on your machine and have run the command GCloud Auth Login, your identity can be used as a proxy to test code calling APIs from that machine.
  3. If you are running in Google Compute Engine production, the built-in service account associated with the virtual machine instance will be used.
  4. If all previous steps have failed, InvalidOperationException is thrown.

Parameter
NameDescription
cancellationTokenCancellationToken

Cancellation token for the operation.

Returns
TypeDescription
TaskGoogleCredential

A task which completes with the application default credentials.

Remarks

If the cancellation token is cancelled while the underlying operation is loading Application Default Credentials, the underlying operation will still be used for any further requests. No actual work is cancelled via this cancellation token; it just allows the returned task to transition to a cancelled state.

GetOidcTokenAsync(OidcTokenOptions, CancellationToken)

public Task<OidcToken> GetOidcTokenAsync(OidcTokenOptions options, CancellationToken cancellationToken = default)

Returns an OIDC token for the given options.

Parameters
NameDescription
optionsOidcTokenOptions

The options to create the token from.

cancellationTokenCancellationToken

The cancellation token that may be used to cancel the request.

Returns
TypeDescription
TaskOidcToken

The OIDC token.

Impersonate(Initializer)

public GoogleCredential Impersonate(ImpersonatedCredential.Initializer initializer)

Allows this credential to impersonate the TargetPrincipal. Only ServiceAccountCredential and UserCredential support impersonation, so this method will throw System.InvalidOperationException if this credential's UnderlyingCredential is not of one of those supported types.

Parameter
NameDescription
initializerImpersonatedCredentialInitializer

Initializer containing the configuration for the impersonated credential.

Returns
TypeDescription
GoogleCredential
Remarks

For impersonation, a credential needs to be scoped to https://www.googleapis.com/auth/iam. When using a ServiceAccountCredential as the source credential, this is not a problem, since the credential can be scoped on demand. When using a UserCredential the credential needs to have been obtained with the required scope, else, when attempting and impersonated request, you'll receive an authorization error.

SignBlobAsync(byte[], CancellationToken)

public Task<string> SignBlobAsync(byte[] blob, CancellationToken cancellationToken = default)

Returns the base64 encoded signature of the given blob.

Parameters
NameDescription
blobbyte

The blob to sign.

cancellationTokenCancellationToken

The cancellation token.

Returns
TypeDescription
Taskstring

The base64 encoded signature.

Explicit Interface Implementations

ITokenAccess.GetAccessTokenForRequestAsync(string, CancellationToken)

Task<string> ITokenAccess.GetAccessTokenForRequestAsync(string authUri, CancellationToken cancellationToken)
Parameters
NameDescription
authUristring
cancellationTokenCancellationToken
Returns
TypeDescription
Taskstring

ITokenAccessWithHeaders.GetAccessTokenWithHeadersForRequestAsync(string, CancellationToken)

Task<AccessTokenWithHeaders> ITokenAccessWithHeaders.GetAccessTokenWithHeadersForRequestAsync(string authUri, CancellationToken cancellationToken)
Parameters
NameDescription
authUristring
cancellationTokenCancellationToken
Returns
TypeDescription
TaskAccessTokenWithHeaders

IConfigurableHttpClientInitializer.Initialize(ConfigurableHttpClient)

void IConfigurableHttpClientInitializer.Initialize(ConfigurableHttpClient httpClient)
Parameter
NameDescription
httpClientConfigurableHttpClient

Extension Method