Google Auth Library for Node.js

repository·main·Indexed 23 days ago

https://github.com/googleapis/google-auth-library-nodejs

The 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.

Tokens
24.3K
Snippets
57
Records
112
Agent score
79%

What's inside google-auth-library

  1. Ways to authenticate with Google APIs

    main

    The 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.
  2. Use Downscoped Client with Credential Access Boundaries

    main

    The DownscopedClient class 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:

    1. Token Broker: An entity with elevated permissions that uses DownscopedClient to generate restricted access tokens from a source credential based on cabRules.
    2. Token Consumer: An entity that receives the restricted token (or uses a refreshHandler to 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;
  3. Use Impersonated Credentials

    main

    The Impersonated class allows an application to create short-lived service account credentials by impersonating a remote service account via the IAM Credentials API.

    Requirements:

    • The sourceClient must have the roles/iam.serviceAccountTokenCreator IAM role.
    • The sourceClient must authenticate with https://www.googleapis.com/auth/cloud-platform or https://www.googleapis.com/auth/iam scopes.

    Usage: Instantiate Impersonated with a sourceClient, a targetPrincipal, and desired targetScopes. You can then use the resulting client to fetch resources 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();
  4. Access Google Cloud resources from Microsoft Azure using Workload Identity Federation

    main

    To access Google Cloud resources from Microsoft Azure, follow these steps:

    Prerequisites

    1. Create a workload identity pool.
    2. Add Azure as an identity provider in the pool (ensure Google organization policy allows federation from Azure).
    3. Configure the Azure tenant for identity federation.
    4. Grant permission to the external identity to impersonate the target service account.

    Setup

    Generate a credential configuration file using the gcloud CLI:

    # 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.json

    Variables:

    • $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.
  5. Access Google Cloud resources from AWS using Workload Identity Federation

    main

    You 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

    1. Create a workload identity pool.
    2. Add AWS as an identity provider in the pool (ensure Google organization policy allows federation from AWS).
    3. Grant permission to the external identity to impersonate the target service account.

    Setup

    Generate a credential configuration file using the gcloud CLI. 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.json

    Variables:

    • $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 the credential_source in your ADC configuration file.

  6. Use External Identities with Application Default Credentials (ADC)

    main

    To use external identities (AWS, Azure, OIDC) with the standard GoogleAuth flow, follow these steps:

    1. Generate the JSON credentials configuration file using gcloud.
    2. Set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of that file.
    export GOOGLE_APPLICATION_CREDENTIALS=/path/to/config.json

    Project ID Discovery: By default, the library attempts to auto-discover the project ID. This requires the roles/browser role to be granted to the service account and the Cloud Resource Manager API to be enabled. To avoid this, provide the projectId explicitly 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...
  7. Explore authentication samples

    main
    The repository includes a comprehensive set of code samples located in the samples/ directory. Each sample contains its own README.md with specific instructions for running that particular example. These samples cover various authentication scenarios including ADC, OAuth2, JWT, and ID Token verification.
  8. Load JWT credentials from environment variables

    main

    For environments like Heroku or App Engine, you can load service account credentials from an environment variable instead of a file.

    1. Export the full JSON credential string to an environment variable (e.g., CREDS).
    2. Parse the variable and pass the fields to the JWT constructor.
    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);
  9. Configure X.509 certificate-sourced credentials

    main

    To use X.509 certificate-sourced credentials, you must generate both a credential configuration file and a certificate configuration file.

    If you omit the --credential-cert-configuration-output-file flag, gcloud creates 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.json

    Custom Location

    Use the --credential-cert-configuration-output-file flag 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.json

    Variables:

    • $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.
  10. Access Google Cloud resources from an OIDC identity provider

    main

    You 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.json

    2. 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.json

    Variables:

    • $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).
  11. Configure Workforce Identity Federation via gcloud CLI

    main

    Workforce 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 gcloud CLI. The library uses this file to exchange external subject tokens for GCP access tokens.

    There are three primary sourcing methods for credentials:

    1. File-sourced: A background process refreshes a local file with a new subject token.
    2. URL-sourced: The library performs a GET request to a local server endpoint to retrieve the token.
    3. 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