Google Auth Library for Node.js
repository·main·Indexed 23 days ago
https://github.com/googleapis/google-auth-library-nodejsThe officially supported client library for implementing OAuth 2.0 authorization and authentication with Google APIs in Node.js. Version 10.5.0 supports multiple authentication strategies, including Application Default Credentials (ADC), OAuth2, JSON Web Tokens (JWT), Google Compute, Workload Identity Federation, Workforce Identity Federation, Impersonated Credentials, and Downscoped Clients.
What's inside google-auth-library
- This library follows Semantic Versioning and is considered stable. The code surface is guaranteed not to change in backwards-incompatible ways unless absolutely necessary (e.g., critical security issues) or after an extensive deprecation period. Issues and requests for stable libraries are prioritized.
Ways to authenticate with Google APIs
mainThe library supports several authentication strategies depending on your use case:
- Application Default Credentials (ADC): Recommended for applications running on Google Cloud or when using a single identity for all users. Supports Workload Identity Federation for non-Google Cloud platforms.
- OAuth2: Use when performing actions on behalf of an end user.
- JSON Web Tokens (JWT): Use for server-to-server or server-to-API communication using a single identity.
- Google Compute: Directly use a service account on Google Cloud Platform for server-to-server communication.
- Workload Identity Federation: Access Google Cloud resources from AWS, Azure, or OIDC-compatible providers without managing local service account keys.
- Workforce Identity Federation: Access Google Cloud services using an external Identity Provider (IdP) for employees, partners, or contractors.
- Impersonated Credentials Client: Access protected resources on behalf of another service account.
- Downscoped Client: Generate short-lived credentials with restricted IAM permissions (e.g., for Cloud Storage) using Credential Access Boundary.
Use Downscoped Client with Credential Access Boundaries
mainThe
DownscopedClientclass is used to restrict IAM permissions of a short-lived credential using Credential Access Boundaries (CAB). This implements the Principle of Least Privilege by ensuring tokens only access specific resources.Note: Currently, only Cloud Storage supports Credential Access Boundaries.
Workflow:
- Token Broker: An entity with elevated permissions that uses
DownscopedClientto generate restricted access tokens from a source credential based oncabRules. - Token Consumer: An entity that receives the restricted token (or uses a
refreshHandlerto fetch it from the broker) to perform operations on specific resources (e.g., a GCS bucket).
const {GoogleAuth, DownscopedClient} = require('google-auth-library'); // Define CAB rules which will restrict the downscoped token to have readonly // access to objects starting with "customer-a" in bucket "bucket_name". const cabRules = { accessBoundary: { accessBoundaryRules: [ { availableResource: `//storage.googleapis.com/projects/_/buckets/bucket_name`, availablePermissions: ['inRole:roles/storage.objectViewer'], availabilityCondition: { expression: `resource.name.startsWith('projects/_/buckets/` + `bucket_name/objects/customer-a)` } }, ], }, }; // This will use ADC to get the credentials used for the downscoped client. const googleAuth = new GoogleAuth({ scopes: ['https://www.googleapis.com/auth/cloud-platform'] }); // Obtain an authenticated client via ADC. const client = await googleAuth.getClient(); // Use the client to create a DownscopedClient. const cabClient = new DownscopedClient({authClient: client, credentialAccessBoundary: cab}); // Refresh the tokens. const refreshedAccessToken = await cabClient.getAccessToken(); // This will need to be passed to the token consumer. access_token = refreshedAccessToken.token; expiry_date = refreshedAccessToken.expirationTime;- Token Broker: An entity with elevated permissions that uses
Use Impersonated Credentials
mainThe
Impersonatedclass allows an application to create short-lived service account credentials by impersonating a remote service account via the IAM Credentials API.Requirements:
- The
sourceClientmust have theroles/iam.serviceAccountTokenCreatorIAM role. - The
sourceClientmust authenticate withhttps://www.googleapis.com/auth/cloud-platformorhttps://www.googleapis.com/auth/iamscopes.
Usage: Instantiate
Impersonatedwith asourceClient, atargetPrincipal, and desiredtargetScopes. You can then use the resulting client tofetchresources directly or pass it to Google Cloud client libraries (like Secret Manager or KMS) that utilize gRPC.const { GoogleAuth, Impersonated } = require('google-auth-library'); const { SecretManagerServiceClient } = require('@google-cloud/secret-manager'); async function main() { // Acquire source credentials: const auth = new GoogleAuth(); const client = await auth.getClient(); // Impersonate new credentials: let targetClient = new Impersonated({ sourceClient: client, targetPrincipal: 'impersonated-account@projectID.iam.gserviceaccount.com', lifetime: 30, delegates: [], targetScopes: ['https://www.googleapis.com/auth/cloud-platform'] }); // Get impersonated credentials: const authHeaders = await targetClient.getRequestHeaders(); // Do something with `authHeaders.get('authorization')`. // Use impersonated credentials: const url = 'https://www.googleapis.com/storage/v1/b?project=anotherProjectID' const resp = await targetClient.fetch(url); for (const bucket of resp.data.items) { console.log(bucket.name); } // Use impersonated credentials with google-cloud client library // Note: this works only with certain cloud client libraries utilizing gRPC // e.g. SecretManager, KMS, AIPlatform // will not currently work with libraries using REST, e.g. Storage, Compute const smClient = new SecretManagerServiceClient({ projectId: anotherProjectID, auth: { getClient: () => targetClient, }, }); const secretName = 'projects/anotherProjectNumber/secrets/someProjectName/versions/1'; const [accessResponse] = await smClient.accessSecretVersion({ name: secretName, }); const responsePayload = accessResponse.payload.data.toString('utf8'); // Do something with the secret contained in `responsePayload`. }; main();- The
Access Google Cloud resources from Microsoft Azure using Workload Identity Federation
mainTo access Google Cloud resources from Microsoft Azure, follow these steps:
Prerequisites
- Create a workload identity pool.
- Add Azure as an identity provider in the pool (ensure Google organization policy allows federation from Azure).
- Configure the Azure tenant for identity federation.
- Grant permission to the external identity to impersonate the target service account.
Setup
Generate a credential configuration file using the
gcloudCLI:# Generate an Azure configuration file. gcloud iam workload-identity-pools create-cred-config \ projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AZURE_PROVIDER_ID \ --service-account $SERVICE_ACCOUNT_EMAIL \ --azure \ --output-file /path/to/generated/config.jsonVariables:
$PROJECT_NUMBER: Google Cloud project number.$POOL_ID: Workload identity pool ID.$AZURE_PROVIDER_ID: Azure provider ID.$SERVICE_ACCOUNT_EMAIL: Email of the service account to impersonate.
Access Google Cloud resources from AWS using Workload Identity Federation
mainYou can access Google Cloud resources from AWS without using service account keys by using Workload Identity Federation. This allows your AWS workload to impersonate a Google Cloud service account.
Prerequisites
- Create a workload identity pool.
- Add AWS as an identity provider in the pool (ensure Google organization policy allows federation from AWS).
- Grant permission to the external identity to impersonate the target service account.
Setup
Generate a credential configuration file using the
gcloudCLI. This file contains non-sensitive metadata used by the Auth library to exchange AWS tokens for Google service account tokens.# Generate an AWS configuration file. gcloud iam workload-identity-pools create-cred-config \ projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AWS_PROVIDER_ID \ --service-account $SERVICE_ACCOUNT_EMAIL \ --aws \ --output-file /path/to/generated/config.jsonVariables:
$PROJECT_NUMBER: Google Cloud project number.$POOL_ID: Workload identity pool ID.$AWS_PROVIDER_ID: AWS provider ID.$SERVICE_ACCOUNT_EMAIL: Email of the service account to impersonate.
Note on IMDSv2: If using AWS IMDSv2, add
"imdsv2_session_token_url": "http://169.254.169.254/latest/api/token"to thecredential_sourcein your ADC configuration file.Use External Identities with Application Default Credentials (ADC)
mainTo use external identities (AWS, Azure, OIDC) with the standard
GoogleAuthflow, follow these steps:- Generate the JSON credentials configuration file using
gcloud. - Set the
GOOGLE_APPLICATION_CREDENTIALSenvironment variable to the path of that file.
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/config.jsonProject ID Discovery: By default, the library attempts to auto-discover the project ID. This requires the
roles/browserrole to be granted to the service account and theCloud Resource Manager APIto be enabled. To avoid this, provide theprojectIdexplicitly during initialization.const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/cloud-platform', // Pass the project ID explicitly to avoid the need to grant `roles/browser` // or enable Cloud Resource Manager API on the project. projectId: 'CLOUD_RESOURCE_PROJECT_ID', }); const projectId = await auth.getProjectId(); // Use the auth instance to make requests...- Generate the JSON credentials configuration file using
Explore authentication samples
mainThe repository includes a comprehensive set of code samples located in thesamples/directory. Each sample contains its ownREADME.mdwith specific instructions for running that particular example. These samples cover various authentication scenarios including ADC, OAuth2, JWT, and ID Token verification.Load JWT credentials from environment variables
mainFor environments like Heroku or App Engine, you can load service account credentials from an environment variable instead of a file.
- Export the full JSON credential string to an environment variable (e.g.,
CREDS). - Parse the variable and pass the fields to the
JWTconstructor.
const {JWT} = require('google-auth-library'); const keysEnvVar = process.env['CREDS']; if (!keysEnvVar) { throw new Error('The $CREDS environment variable was not found!'); } const keys = JSON.parse(keysEnvVar); const client = new JWT({ email: keys.client_email, key: keys.private_key, scopes: ['https://www.googleapis.com/auth/cloud-platform'], });const {JWT} = require('google-auth-library'); // load the environment variable with our keys const keysEnvVar = process.env['CREDS']; if (!keysEnvVar) { throw new Error('The $CREDS environment variable was not found!'); } const keys = JSON.parse(keysEnvVar); // create a JWT client const client = new JWT({ email: keys.client_email, key: keys.private_key, scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`; const res = await client.fetch(url); console.log(res.data);- Export the full JSON credential string to an environment variable (e.g.,
Configure X.509 certificate-sourced credentials
mainTo use X.509 certificate-sourced credentials, you must generate both a credential configuration file and a certificate configuration file.
Default Behavior (Recommended)
If you omit the
--credential-cert-configuration-output-fileflag,gcloudcreates the certificate configuration file at a default location (e.g.,~/.config/gcloud/certificate_config.json) that client libraries can automatically discover.# Example Command (Default Behavior): gcloud iam workload-identity-pools create-cred-config \ projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$PROVIDER_ID \ --service-account $SERVICE_ACCOUNT_EMAIL \ --credential-cert-path "$PATH_TO_CERTIFICATE" \ --credential-cert-private-key-path "$PATH_TO_PRIVATE_KEY" \ --credential-cert-trust-chain-path "$PATH_TO_TRUST_CHAIN" \ --output-file /path/to/config.jsonCustom Location
Use the
--credential-cert-configuration-output-fileflag to specify a non-default location for the certificate configuration file.# Example Command (Custom Location): gcloud iam workload-identity-pools create-cred-config \ projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$PROVIDER_ID \ --service-account $SERVICE_ACCOUNT_EMAIL \ --credential-cert-path "$PATH_TO_CERTIFICATE" \ --credential-cert-private-key-path "$PATH_TO_PRIVATE_KEY" \ --credential-cert-trust-chain-path "$PATH_TO_TRUST_CHAIN" \ --credential-cert-configuration-output-file "/custom/path/cert_config.json" \ --output-file /path/to/config.jsonVariables:
$PATH_TO_CERTIFICATE: Path to your leaf X.509 certificate.$PATH_TO_PRIVATE_KEY: Path to the corresponding private key (.key).$PATH_TO_TRUST_CHAIN: Path to the X.509 certificate trust chain file.
Access Google Cloud resources from an OIDC identity provider
mainYou can use an OpenID Connect (OIDC) provider via Workload Identity Federation. The Auth library supports two methods for retrieving OIDC tokens:
1. File-sourced credentials
Requires a background process to continuously refresh a local file with a new OIDC token before it expires.
# Generate a file-sourced OIDC configuration. gcloud iam workload-identity-pools create-cred-config \ projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$OIDC_PROVIDER_ID \ --service-account $SERVICE_ACCOUNT_EMAIL \ --credential-source-file $PATH_TO_OIDC_ID_TOKEN \ --output-file /path/to/generated/config.json2. URL-sourced credentials
A local server must host a GET endpoint that returns the OIDC token (plain text or JSON).
# Generate a URL-sourced OIDC configuration. gcloud iam workload-identity-pools create-cred-config \ projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$OIDC_PROVIDER_ID \ --service-account $SERVICE_ACCOUNT_EMAIL \ --credential-source-url $URL_TO_GET_OIDC_TOKEN \ --credential-source-headers $HEADER_KEY=$HEADER_VALUE \ --output-file /path/to/generated/config.jsonVariables:
$PATH_TO_OIDC_ID_TOKEN: Path to the file containing the OIDC token.$URL_TO_GET_OIDC_TOKEN: URL of the local server endpoint.$HEADER_KEY/$HEADER_VALUE: Additional headers for the GET request (e.g.,Metadata-Flavor=Google).
Configure Workforce Identity Federation via gcloud CLI
mainWorkforce identity federation allows using external IdPs (OIDC or SAML 2.0) to access Google Cloud. To use this with the Auth library, you must first generate a credential configuration file using the
gcloudCLI. The library uses this file to exchange external subject tokens for GCP access tokens.There are three primary sourcing methods for credentials:
- File-sourced: A background process refreshes a local file with a new subject token.
- URL-sourced: The library performs a GET request to a local server endpoint to retrieve the token.
- Executable-sourced: The library runs a local executable that outputs the token to stdout.
Refer to the specific commands below for your chosen method.
# Example: Generate an OIDC configuration file for file-sourced credentials. gcloud iam workforce-pools create-cred-config \ locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ --subject-token-type=urn:ietf:params:oauth:token-type:id_token \ --credential-source-file=$PATH_TO_OIDC_ID_TOKEN \ --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ --output-file=/path/to/generated/config.json