Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

google-auth-library

googleapis44.6mApache-2.09.15.0TypeScript support: included

Google APIs Authentication Client Library for Node.js

google, api, google apis, client, client library

readme

Google Cloud Platform logo

Google Auth Library: Node.js Client

release level npm version

This is Google's officially supported node.js client library for using OAuth 2.0 authorization and authentication with Google APIs.

A comprehensive list of changes in each version may be found in the CHANGELOG.

Read more about the client libraries for Cloud APIs, including the older Google APIs Client Libraries, in Client Libraries Explained.

Table of contents:

Quickstart

Installing the client library

npm install google-auth-library

Ways to authenticate

This library provides a variety of ways to authenticate to your Google services.

  • Application Default Credentials - Use Application Default Credentials when you use a single identity for all users in your application. Especially useful for applications running on Google Cloud. Application Default Credentials also support workload identity federation to access Google Cloud resources from non-Google Cloud platforms.
  • OAuth 2 - Use OAuth2 when you need to perform actions on behalf of the end user.
  • JSON Web Tokens - Use JWT when you are using a single identity for all users. Especially useful for server->server or server->API communication.
  • Google Compute - Directly use a service account on Google Cloud Platform. Useful for server->server or server->API communication.
  • Workload Identity Federation - Use workload identity federation to access Google Cloud resources from Amazon Web Services (AWS), Microsoft Azure or any identity provider that supports OpenID Connect (OIDC).
  • Workforce Identity Federation - Use workforce identity federation to access Google Cloud resources using an external identity provider (IdP) to authenticate and authorize a workforce—a group of users, such as employees, partners, and contractors—using IAM, so that the users can access Google Cloud services.
  • Impersonated Credentials Client - access protected resources on behalf of another service account.
  • Downscoped Client - Use Downscoped Client with Credential Access Boundary to generate a short-lived credential with downscoped, restricted IAM permissions that can use for Cloud Storage.

Application Default Credentials

This library provides an implementation of Application Default Credentials for Node.js. The Application Default Credentials provide a simple way to get authorization credentials for use in calling Google APIs.

They are best suited for cases when the call needs to have the same identity and authorization level for the application independent of the user. This is the recommended approach to authorize calls to Cloud APIs, particularly when you're building an application that uses Google Cloud Platform.

Application Default Credentials also support workload identity federation to access Google Cloud resources from non-Google Cloud platforms including Amazon Web Services (AWS), Microsoft Azure or any identity provider that supports OpenID Connect (OIDC). Workload identity federation is recommended for non-Google Cloud environments as it avoids the need to download, manage and store service account private keys locally, see: Workload Identity Federation.

Download your Service Account Credentials JSON file

To use Application Default Credentials, You first need to download a set of JSON credentials for your project. Go to APIs & Auth > Credentials in the Google Developers Console and select Service account from the Add credentials dropdown.

This file is your only copy of these credentials. It should never be committed with your source code, and should be stored securely.

Once downloaded, store the path to this file in the GOOGLE_APPLICATION_CREDENTIALS environment variable.

Enable the API you want to use

Before making your API call, you must be sure the API you're calling has been enabled. Go to APIs & Auth > APIs in the Google Developers Console and enable the APIs you'd like to call. For the example below, you must enable the DNS API.

Choosing the correct credential type automatically

Rather than manually creating an OAuth2 client, JWT client, or Compute client, the auth library can create the correct credential type for you, depending upon the environment your code is running under.

For example, a JWT auth client will be created when your code is running on your local developer machine, and a Compute client will be created when the same code is running on Google Cloud Platform. If you need a specific set of scopes, you can pass those in the form of a string or an array to the GoogleAuth constructor.

The code below shows how to retrieve a default credential type, depending upon the runtime environment.

const {GoogleAuth} = require('google-auth-library');

/**
* Instead of specifying the type of client you'd like to use (JWT, OAuth2, etc)
* this library will automatically choose the right client based on the environment.
*/
async function main() {
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/cloud-platform'
  });
  const client = await auth.getClient();
  const projectId = await auth.getProjectId();
  const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
  const res = await client.request({ url });
  console.log(res.data);
}

main().catch(console.error);

OAuth2

This library comes with an OAuth2 client that allows you to retrieve an access token and refreshes the token and retry the request seamlessly if you also provide an expiry_date and the token is expired. The basics of Google's OAuth2 implementation is explained on Google Authorization and Authentication documentation.

In the following examples, you may need a CLIENT_ID, CLIENT_SECRET and REDIRECT_URL. You can find these pieces of information by going to the Developer Console, clicking your project > APIs & auth > credentials.

For more information about OAuth2 and how it works, see here.

A complete OAuth2 example

Let's take a look at a complete example.

const {OAuth2Client} = require('google-auth-library');
const http = require('http');
const url = require('url');
const open = require('open');
const destroyer = require('server-destroy');

// Download your OAuth2 configuration from the Google
const keys = require('./oauth2.keys.json');

/**
* Start by acquiring a pre-authenticated oAuth2 client.
*/
async function main() {
  const oAuth2Client = await getAuthenticatedClient();
  // Make a simple request to the People API using our pre-authenticated client. The `request()` method
  // takes an GaxiosOptions object.  Visit https://github.com/JustinBeckwith/gaxios.
  const url = 'https://people.googleapis.com/v1/people/me?personFields=names';
  const res = await oAuth2Client.request({url});
  console.log(res.data);

  // After acquiring an access_token, you may want to check on the audience, expiration,
  // or original scopes requested.  You can do that with the `getTokenInfo` method.
  const tokenInfo = await oAuth2Client.getTokenInfo(
    oAuth2Client.credentials.access_token
  );
  console.log(tokenInfo);
}

/**
* Create a new OAuth2Client, and go through the OAuth2 content
* workflow.  Return the full client to the callback.
*/
function getAuthenticatedClient() {
  return new Promise((resolve, reject) => {
    // create an oAuth client to authorize the API call.  Secrets are kept in a `keys.json` file,
    // which should be downloaded from the Google Developers Console.
    const oAuth2Client = new OAuth2Client(
      keys.web.client_id,
      keys.web.client_secret,
      keys.web.redirect_uris[0]
    );

    // Generate the url that will be used for the consent dialog.
    const authorizeUrl = oAuth2Client.generateAuthUrl({
      access_type: 'offline',
      scope: 'https://www.googleapis.com/auth/userinfo.profile',
    });

    // Open an http server to accept the oauth callback. In this simple example, the
    // only request to our webserver is to /oauth2callback?code=<code>
    const server = http
      .createServer(async (req, res) => {
        try {
          if (req.url.indexOf('/oauth2callback') > -1) {
            // acquire the code from the querystring, and close the web server.
            const qs = new url.URL(req.url, 'http://localhost:3000')
              .searchParams;
            const code = qs.get('code');
            console.log(`Code is ${code}`);
            res.end('Authentication successful! Please return to the console.');
            server.destroy();

            // Now that we have the code, use that to acquire tokens.
            const r = await oAuth2Client.getToken(code);
            // Make sure to set the credentials on the OAuth2 client.
            oAuth2Client.setCredentials(r.tokens);
            console.info('Tokens acquired.');
            resolve(oAuth2Client);
          }
        } catch (e) {
          reject(e);
        }
      })
      .listen(3000, () => {
        // open the browser to the authorize url to start the workflow
        open(authorizeUrl, {wait: false}).then(cp => cp.unref());
      });
    destroyer(server);
  });
}

main().catch(console.error);

Handling token events

This library will automatically obtain an access_token, and automatically refresh the access_token if a refresh_token is present. The refresh_token is only returned on the first authorization, so if you want to make sure you store it safely. An easy way to make sure you always store the most recent tokens is to use the tokens event:

const client = await auth.getClient();

client.on('tokens', (tokens) => {
  if (tokens.refresh_token) {
    // store the refresh_token in my database!
    console.log(tokens.refresh_token);
  }
  console.log(tokens.access_token);
});

const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.request({ url });
// The `tokens` event would now be raised if this was the first request

Retrieve access token

With the code returned, you can ask for an access token as shown below:

const tokens = await oauth2Client.getToken(code);
// Now tokens contains an access_token and an optional refresh_token. Save them.
oauth2Client.setCredentials(tokens);

Obtaining a new Refresh Token

If you need to obtain a new refresh_token, ensure the call to generateAuthUrl sets the access_type to offline. The refresh token will only be returned for the first authorization by the user. To force consent, set the prompt property to consent:

// Generate the url that will be used for the consent dialog.
const authorizeUrl = oAuth2Client.generateAuthUrl({
  // To get a refresh token, you MUST set access_type to `offline`.
  access_type: 'offline',
  // set the appropriate scopes
  scope: 'https://www.googleapis.com/auth/userinfo.profile',
  // A refresh token is only returned the first time the user
  // consents to providing access.  For illustration purposes,
  // setting the prompt to 'consent' will force this consent
  // every time, forcing a refresh_token to be returned.
  prompt: 'consent'
});

Checking access_token information

After obtaining and storing an access_token, at a later time you may want to go check the expiration date, original scopes, or audience for the token. To get the token info, you can use the getTokenInfo method:

// after acquiring an oAuth2Client...
const tokenInfo = await oAuth2Client.getTokenInfo('my-access-token');

// take a look at the scopes originally provisioned for the access token
console.log(tokenInfo.scopes);

This method will throw if the token is invalid.

Using an API Key

An API key can be provided to the constructor:

const client = new OAuth2Client({
  apiKey: 'my-api-key'
});

Note, classes that extend from this can utilize this parameter as well, such as JWT and UserRefreshClient.

Additionally, an API key can be used in GoogleAuth via the clientOptions parameter and will be passed to any generated OAuth2Client instances:

const auth = new GoogleAuth({
  clientOptions: {
    apiKey: 'my-api-key'
  }
})

API Key support varies by API.

JSON Web Tokens

The Google Developers Console provides a .json file that you can use to configure a JWT auth client and authenticate your requests, for example when using a service account.

const {JWT} = require('google-auth-library');
const keys = require('./jwt.keys.json');

async function main() {
  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.request({url});
  console.log(res.data);
}

main().catch(console.error);

The parameters for the JWT auth client including how to use it with a .pem file are explained in samples/jwt.js.

Loading credentials from environment variables

Instead of loading credentials from a key file, you can also provide them using an environment variable and the GoogleAuth.fromJSON() method. This is particularly convenient for systems that deploy directly from source control (Heroku, App Engine, etc).

Start by exporting your credentials:

$ export CREDS='{
  "type": "service_account",
  "project_id": "your-project-id",
  "private_key_id": "your-private-key-id",
  "private_key": "your-private-key",
  "client_email": "your-client-email",
  "client_id": "your-client-id",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "your-cert-url"
}'

Now you can create a new client from the credentials:

const {auth} = 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);

async function main() {
  // load the JWT or UserRefreshClient from the keys
  const client = auth.fromJSON(keys);
  client.scopes = ['https://www.googleapis.com/auth/cloud-platform'];
  const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`;
  const res = await client.request({url});
  console.log(res.data);
}

main().catch(console.error);

Using a Proxy

You can set the HTTPS_PROXY or https_proxy environment variables to proxy HTTPS requests. When HTTPS_PROXY or https_proxy are set, they will be used to proxy SSL requests that do not have an explicit proxy configuration option present.

Compute

If your application is running on Google Cloud Platform, you can authenticate using the default service account or by specifying a specific service account.

Note: In most cases, you will want to use Application Default Credentials. Direct use of the Compute class is for very specific scenarios.

const {auth, Compute} = require('google-auth-library');

async function main() {
  const client = new Compute({
    // Specifying the service account email is optional.
    serviceAccountEmail: 'my-service-account@example.com'
  });
  const projectId = await auth.getProjectId();
  const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`;
  const res = await client.request({url});
  console.log(res.data);
}

main().catch(console.error);

Workload Identity Federation

Using workload identity federation, your application can access Google Cloud resources from Amazon Web Services (AWS), Microsoft Azure or any identity provider that supports OpenID Connect (OIDC).

Traditionally, applications running outside Google Cloud have used service account keys to access Google Cloud resources. Using identity federation, you can allow your workload to impersonate a service account. This lets you access Google Cloud resources directly, eliminating the maintenance and security burden associated with service account keys.

Accessing resources from AWS

In order to access Google Cloud resources from Amazon Web Services (AWS), the following requirements are needed:

  • A workload identity pool needs to be created.
  • AWS needs to be added as an identity provider in the workload identity pool (The Google organization policy needs to allow federation from AWS).
  • Permission to impersonate a service account needs to be granted to the external identity.

Follow the detailed instructions on how to configure workload identity federation from AWS.

After configuring the AWS provider to impersonate a service account, a credential configuration file needs to be generated. Unlike service account credential files, the generated credential configuration file will only contain non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for service account access tokens. The configuration file can be generated by using the gcloud CLI.

To generate the AWS workload identity configuration, run the following command:

# 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

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $POOL_ID: The workload identity pool ID.
  • $AWS_PROVIDER_ID: The AWS provider ID.
  • $SERVICE_ACCOUNT_EMAIL: The email of the service account to impersonate.

This will generate the configuration file in the specified output file.

If you want to use the AWS IMDSv2 flow, you can add the field below to the credential_source in your AWS ADC configuration file: "imdsv2_session_token_url": "http://169.254.169.254/latest/api/token" The gcloud create-cred-config command will be updated to support this soon.

You can now start using the Auth library to call Google Cloud resources from AWS.

Accessing resources from AWS using a custom AWS security credentials supplier.

In order to access Google Cloud resources from Amazon Web Services (AWS), the following requirements are needed:

  • A workload identity pool needs to be created.
  • AWS needs to be added as an identity provider in the workload identity pool (The Google organization policy needs to allow federation from AWS).
  • Permission to impersonate a service account needs to be granted to the external identity.

Follow the detailed instructions on how to configure workload identity federation from AWS.

If you want to use AWS security credentials that cannot be retrieved using methods supported natively by this library, a custom AwsSecurityCredentialsSupplier implementation may be specified when creating an AWS client. The supplier must return valid, unexpired AWS security credentials when called by the GCP credential. Currently, using ADC with your AWS workloads is only supported with EC2. An example of a good use case for using a custom credential suppliers is when your workloads are running in other AWS environments, such as ECS, EKS, Fargate, etc.

Note that the client does not cache the returned AWS security credentials, so caching logic should be implemented in the supplier to prevent multiple requests for the same resources.

import { AwsClient, AwsSecurityCredentials, AwsSecurityCredentialsSupplier, ExternalAccountSupplierContext } from 'google-auth-library';
import { fromNodeProviderChain } from '@aws-sdk/credential-providers';
import { Storage } from '@google-cloud/storage';

class AwsSupplier implements AwsSecurityCredentialsSupplier {
  private readonly region: string

  constructor(region: string) {
    this.region = options.region;
  }

  async getAwsRegion(context: ExternalAccountSupplierContext): Promise<string> {
    // Return the AWS region i.e. "us-east-2".
    return this.region
  }

  async getAwsSecurityCredentials(
    context: ExternalAccountSupplierContext
  ): Promise<AwsSecurityCredentials> {
    // Retrieve the AWS credentails.
    const awsCredentialsProvider = fromNodeProviderChain();
    const awsCredentials = await awsCredentialsProvider();

    // Parse the AWS credentials into a AWS security credentials instance and
    // return them.
    const awsSecurityCredentials = {
      accessKeyId: awsCredentials.accessKeyId,
      secretAccessKey: awsCredentials.secretAccessKey,
      token: awsCredentials.sessionToken
    }
    return awsSecurityCredentials;
  }
}

const clientOptions = {
  audience: '//iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID', // Set the GCP audience.
  subject_token_type: 'urn:ietf:params:aws:token-type:aws4_request', // Set the subject token type.
  aws_security_credentials_supplier: new AwsSupplier("AWS_REGION") // Set the custom supplier.
}

// Create a new Auth client and use it to create service client, i.e. storage.
const authClient = new AwsClient(clientOptions);
const storage = new Storage({ authClient });

Where the audience is: //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $WORKLOAD_POOL_ID: The workload pool ID.
  • $PROVIDER_ID: The provider ID.

The values for audience, service account impersonation URL, and any other builder field can also be found by generating a credential configuration file with the gcloud CLI.

Access resources from Microsoft Azure

In order to access Google Cloud resources from Microsoft Azure, the following requirements are needed:

  • A workload identity pool needs to be created.
  • Azure needs to be added as an identity provider in the workload identity pool (The Google organization policy needs to allow federation from Azure).
  • The Azure tenant needs to be configured for identity federation.
  • Permission to impersonate a service account needs to be granted to the external identity.

Follow the detailed instructions on how to configure workload identity federation from Microsoft Azure.

After configuring the Azure provider to impersonate a service account, a credential configuration file needs to be generated. Unlike service account credential files, the generated credential configuration file will only contain non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for service account access tokens. The configuration file can be generated by using the gcloud CLI.

To generate the Azure workload identity configuration, run the following command:

# 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

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $POOL_ID: The workload identity pool ID.
  • $AZURE_PROVIDER_ID: The Azure provider ID.
  • $SERVICE_ACCOUNT_EMAIL: The email of the service account to impersonate.

This will generate the configuration file in the specified output file.

You can now start using the Auth library to call Google Cloud resources from Azure.

Accessing resources from an OIDC identity provider

In order to access Google Cloud resources from an identity provider that supports OpenID Connect (OIDC), the following requirements are needed:

  • A workload identity pool needs to be created.
  • An OIDC identity provider needs to be added in the workload identity pool (The Google organization policy needs to allow federation from the identity provider).
  • Permission to impersonate a service account needs to be granted to the external identity.

Follow the detailed instructions on how to configure workload identity federation from an OIDC identity provider.

After configuring the OIDC provider to impersonate a service account, a credential configuration file needs to be generated. Unlike service account credential files, the generated credential configuration file will only contain non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for service account access tokens. The configuration file can be generated by using the gcloud CLI.

For OIDC providers, the Auth library can retrieve OIDC tokens either from a local file location (file-sourced credentials) or from a local server (URL-sourced credentials).

File-sourced credentials For file-sourced credentials, a background process needs to be continuously refreshing the file location with a new OIDC token prior to expiration. For tokens with one hour lifetimes, the token needs to be updated in the file every hour. The token can be stored directly as plain text or in JSON format.

To generate a file-sourced OIDC configuration, run the following command:

# Generate an OIDC configuration file for file-sourced credentials.
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 \
    # Optional arguments for file types. Default is "text":
    # --credential-source-type "json" \
    # Optional argument for the field that contains the OIDC credential.
    # This is required for json.
    # --credential-source-field-name "id_token" \
    --output-file /path/to/generated/config.json

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $POOL_ID: The workload identity pool ID.
  • $OIDC_PROVIDER_ID: The OIDC provider ID.
  • $SERVICE_ACCOUNT_EMAIL: The email of the service account to impersonate.
  • $PATH_TO_OIDC_ID_TOKEN: The file path where the OIDC token will be retrieved from.

This will generate the configuration file in the specified output file.

URL-sourced credentials For URL-sourced credentials, a local server needs to host a GET endpoint to return the OIDC token. The response can be in plain text or JSON. Additional required request headers can also be specified.

To generate a URL-sourced OIDC workload identity configuration, run the following command:

# Generate an OIDC configuration file for URL-sourced credentials.
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 \
    # Optional arguments for file types. Default is "text":
    # --credential-source-type "json" \
    # Optional argument for the field that contains the OIDC credential.
    # This is required for json.
    # --credential-source-field-name "id_token" \
    --output-file /path/to/generated/config.json

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $POOL_ID: The workload identity pool ID.
  • $OIDC_PROVIDER_ID: The OIDC provider ID.
  • $SERVICE_ACCOUNT_EMAIL: The email of the service account to impersonate.
  • $URL_TO_GET_OIDC_TOKEN: The URL of the local server endpoint to call to retrieve the OIDC token.
  • $HEADER_KEY and $HEADER_VALUE: The additional header key/value pairs to pass along the GET request to $URL_TO_GET_OIDC_TOKEN, e.g. Metadata-Flavor=Google.

Accessing resources from an OIDC or SAML2.0 identity provider using a custom supplier

If you want to use OIDC or SAML2.0 that cannot be retrieved using methods supported natively by this library, a custom SubjectTokenSupplier implementation may be specified when creating an identity pool client. The supplier must return a valid, unexpired subject token when called by the GCP credential.

Note that the client does not cache the returned subject token, so caching logic should be implemented in the supplier to prevent multiple requests for the same resources.

class CustomSupplier implements SubjectTokenSupplier {
  async getSubjectToken(
    context: ExternalAccountSupplierContext
  ): Promise<string> {
    const audience = context.audience;
    const subjectTokenType = context.subjectTokenType;
    // Return a valid subject token for the requested audience and subject token type.
  }
}

const clientOptions = {
  audience: '//iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID', // Set the GCP audience.
  subject_token_type: 'urn:ietf:params:oauth:token-type:id_token', // Set the subject token type.
  subject_token_supplier: new CustomSupplier() // Set the custom supplier.
}

const client = new CustomSupplier(clientOptions);

Where the audience is: //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $WORKLOAD_POOL_ID: The workload pool ID.
  • $PROVIDER_ID: The provider ID.

The values for audience, service account impersonation URL, and any other builder field can also be found by generating a credential configuration file with the gcloud CLI.

Using External Account Authorized User workforce credentials

External account authorized user credentials allow you to sign in with a web browser to an external identity provider account via the gcloud CLI and create a configuration for the auth library to use.

To generate an external account authorized user workforce identity configuration, run the following command:

gcloud auth application-default login --login-config=$LOGIN_CONFIG

Where the following variable needs to be substituted:

This will open a browser flow for you to sign in via the configured third party identity provider and then will store the external account authorized user configuration at the well known ADC location. The auth library will then use the provided refresh token from the configuration to generate and refresh an access token to call Google Cloud services.

Note that the default lifetime of the refresh token is one hour, after which a new configuration will need to be generated from the gcloud CLI. The lifetime can be modified by changing the session duration of the workforce pool, and can be set as high as 12 hours.

Using Executable-sourced credentials with OIDC and SAML

Executable-sourced credentials For executable-sourced credentials, a local executable is used to retrieve the 3rd party token. The executable must handle providing a valid, unexpired OIDC ID token or SAML assertion in JSON format to stdout.

To use executable-sourced credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable must be set to 1.

To generate an executable-sourced workload identity configuration, run the following command:

# Generate a configuration file for executable-sourced credentials.
gcloud iam workload-identity-pools create-cred-config \
    projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$PROVIDER_ID \
    --service-account=$SERVICE_ACCOUNT_EMAIL \
    --subject-token-type=$SUBJECT_TOKEN_TYPE \
    # The absolute path for the program, including arguments.
    # e.g. --executable-command="/path/to/command --foo=bar"
    --executable-command=$EXECUTABLE_COMMAND \
    # Optional argument for the executable timeout. Defaults to 30s.
    # --executable-timeout-millis=$EXECUTABLE_TIMEOUT \
    # Optional argument for the absolute path to the executable output file.
    # See below on how this argument impacts the library behaviour.
    # --executable-output-file=$EXECUTABLE_OUTPUT_FILE \
    --output-file /path/to/generated/config.json

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $POOL_ID: The workload identity pool ID.
  • $PROVIDER_ID: The OIDC or SAML provider ID.
  • $SERVICE_ACCOUNT_EMAIL: The email of the service account to impersonate.
  • $SUBJECT_TOKEN_TYPE: The subject token type.
  • $EXECUTABLE_COMMAND: The full command to run, including arguments. Must be an absolute path to the program.

The --executable-timeout-millis flag is optional. This is the duration for which the auth library will wait for the executable to finish, in milliseconds. Defaults to 30 seconds when not provided. The maximum allowed value is 2 minutes. The minimum is 5 seconds.

The --executable-output-file flag is optional. If provided, the file path must point to the 3PI credential response generated by the executable. This is useful for caching the credentials. By specifying this path, the Auth libraries will first check for its existence before running the executable. By caching the executable JSON response to this file, it improves performance as it avoids the need to run the executable until the cached credentials in the output file are expired. The executable must handle writing to this file - the auth libraries will only attempt to read from this location. The format of contents in the file should match the JSON format expected by the executable shown below.

To retrieve the 3rd party token, the library will call the executable using the command specified. The executable's output must adhere to the response format specified below. It must output the response to stdout.

A sample successful executable OIDC response:

{
  "version": 1,
  "success": true,
  "token_type": "urn:ietf:params:oauth:token-type:id_token",
  "id_token": "HEADER.PAYLOAD.SIGNATURE",
  "expiration_time": 1620499962
}

A sample successful executable SAML response:

{
  "version": 1,
  "success": true,
  "token_type": "urn:ietf:params:oauth:token-type:saml2",
  "saml_response": "...",
  "expiration_time": 1620499962
}

For successful responses, the expiration_time field is only required when an output file is specified in the credential configuration.

A sample executable error response:

{
  "version": 1,
  "success": false,
  "code": "401",
  "message": "Caller not authorized."
}

These are all required fields for an error response. The code and message fields will be used by the library as part of the thrown exception.

Response format fields summary:

  • version: The version of the JSON output. Currently, only version 1 is supported.
  • success: The status of the response. When true, the response must contain the 3rd party token and token type. The response must also contain the expiration time if an output file was specified in the credential configuration. The executable must also exit with exit code 0. When false, the response must contain the error code and message fields and exit with a non-zero value.
  • token_type: The 3rd party subject token type. Must be urn:ietf:params:oauth:token-type:jwt, urn:ietf:params:oauth:token-type:id_token, or urn:ietf:params:oauth:token-type:saml2.
  • id_token: The 3rd party OIDC token.
  • saml_response: The 3rd party SAML response.
  • expiration_time: The 3rd party subject token expiration time in seconds (unix epoch time).
  • code: The error code string.
  • message: The error message.

All response types must include both the version and success fields.

  • Successful responses must include the token_type and one of id_token or saml_response. The expiration_time field must also be present if an output file was specified in the credential configuration.
  • Error responses must include both the code and message fields.

The library will populate the following environment variables when the executable is run:

  • GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE: The audience field from the credential configuration. Always present.
  • GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL: The service account email. Only present when service account impersonation is used.
  • GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE: The output file location from the credential configuration. Only present when specified in the credential configuration.
  • GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE: This expected subject token type. Always present.

These environment variables can be used by the executable to avoid hard-coding these values.

Security considerations

The following security practices are highly recommended:

  • Access to the script should be restricted as it will be displaying credentials to stdout. This ensures that rogue processes do not gain access to the script.
  • The configuration file should not be modifiable. Write access should be restricted to avoid processes modifying the executable command portion.

Given the complexity of using executable-sourced credentials, it is recommended to use the existing supported mechanisms (file-sourced/URL-sourced) for providing 3rd party credentials unless they do not meet your specific requirements.

You can now use the Auth library to call Google Cloud resources from an OIDC or SAML provider.

Configurable Token Lifetime

When creating a credential configuration with workload identity federation using service account impersonation, you can provide an optional argument to configure the service account access token lifetime.

To generate the configuration with configurable token lifetime, run the following command (this example uses an AWS configuration, but the token lifetime can be configured for all workload identity federation providers):

# Generate an AWS configuration file with configurable token lifetime.
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 \
    --service-account-token-lifetime-seconds $TOKEN_LIFETIME

Where the following variables need to be substituted:

  • $PROJECT_NUMBER: The Google Cloud project number.
  • $POOL_ID: The workload identity pool ID.
  • $AWS_PROVIDER_ID: The AWS provider ID.
  • $SERVICE_ACCOUNT_EMAIL: The email of the service account to impersonate.
  • $TOKEN_LIFETIME: The desired lifetime duration of the service account access token in seconds.

The service-account-token-lifetime-seconds flag is optional. If not provided, this defaults to one hour. The minimum allowed value is 600 (10 minutes) and the maximum allowed value is 43200 (12 hours). If a lifetime greater than one hour is required, the service account must be added as an allowed value in an Organization Policy that enforces the constraints/iam.allowServiceAccountCredentialLifetimeExtension constraint.

Note that configuring a short lifetime (e.g. 10 minutes) will result in the library initiating the entire token exchange flow every 10 minutes, which will call the 3rd party token provider even if the 3rd party token is not expired.

Workforce Identity Federation

Workforce identity federation lets you use an external identity provider (IdP) to authenticate and authorize a workforce—a group of users, such as employees, partners, and contractors—using IAM, so that the users can access Google Cloud services. Workforce identity federation extends Google Cloud's identity capabilities to support syncless, attribute-based single sign on.

With workforce identity federation, your workforce can access Google Cloud resources using an external identity provider (IdP) that supports OpenID Connect (OIDC) or SAML 2.0 such as Azure Active Directory (Azure AD), Active Directory Federation Services (AD FS), Okta, and others.

Accessing resources using an OIDC or SAML 2.0 identity provider

In order to access Google Cloud resources from an identity provider that supports OpenID Connect (OIDC), the following requirements are needed:

  • A workforce identity pool needs to be created.
  • An OIDC or SAML 2.0 identity provider needs to be added in the workforce pool.

Follow the detailed instructions on how to configure workforce identity federation.

After configuring an OIDC or SAML 2.0 provider, a credential configuration file needs to be generated. The generated credential configuration file contains non-sensitive metadata to instruct the library on how to retrieve external subject tokens and exchange them for GCP access tokens. The configuration file can be generated by using the gcloud CLI.

The Auth library can retrieve external subject tokens from a local file location (file-sourced credentials), from a local server (URL-sourced credentials) or by calling an executable (executable-sourced credentials).

File-sourced credentials For file-sourced credentials, a background process needs to be continuously refreshing the file location with a new subject token prior to expiration. For tokens with one hour lifetimes, the token needs to be updated in the file every hour. The token can be stored directly as plain text or in JSON format.

To generate a file-sourced OIDC configuration, run the following command:

# 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 \
    # Optional arguments for file types. Default is "text":
    # --credential-source-type "json" \
    # Optional argument for the field that contains the OIDC credential.
    # This is required for json.
    # --credential-source-field-name "id_token" \
    --output-file=/path/to/generated/config.json

Where the following variables need to be substituted:

  • $WORKFORCE_POOL_ID: The workforce pool ID.
  • $PROVIDER_ID: The provider ID.
  • $PATH_TO_OIDC_ID_TOKEN: The file path used to retrieve the OIDC token.
  • $WORKFORCE_POOL_USER_PROJECT: The project number associated with the workforce pools user project.

To generate a file-sourced SAML configuration, run the following command:

# Generate a SAML configuration file for file-sourced credentials.
gcloud iam workforce-pools create-cred-config \
    locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \
    --credential-source-file=$PATH_TO_SAML_ASSERTION \
    --subject-token-type=urn:ietf:params:oauth:token-type:saml2 \
    --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \
    --output-file=/path/to/generated/config.json

Where the following variables need to be substituted:

  • $WORKFORCE_POOL_ID: The workforce pool ID.
  • $PROVIDER_ID: The provider ID.
  • $PATH_TO_SAML_ASSERTION: The file path used to retrieve the base64-encoded SAML assertion.
  • $WORKFORCE_POOL_USER_PROJECT: The project number associated with the workforce pools user project.

These commands generate the configuration file in the specified output file.

URL-sourced credentials For URL-sourced credentials, a local server needs to host a GET endpoint to return the OIDC token. The response can be in plain text or JSON. Additional required request headers can also be specified.

To generate a URL-sourced OIDC workforce identity configuration, run the following command:

# Generate an OIDC configuration file for URL-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-url=$URL_TO_RETURN_OIDC_ID_TOKEN \
    --credential-source-headers $HEADER_KEY=$HEADER_VALUE \
    --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \
    --output-file=/path/to/generated/config.json

Where the following variables need to be substituted:

  • $WORKFORCE_POOL_ID: The workforce pool ID.
  • $PROVIDER_ID: The provider ID.
  • $URL_TO_RETURN_OIDC_ID_TOKEN: The URL of the local server endpoint.
  • $HEADER_KEY and $HEADER_VALUE: The additional header key/value pairs to pass along the GET request to $URL_TO_GET_OIDC_TOKEN, e.g. Metadata-Flavor=Google.
  • $WORKFORCE_POOL_USER_PROJECT: The project number associated with the workforce pools user project.

To generate a URL-sourced SAML configuration, run the following command:

# Generate a SAML 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:saml2 \
    --credential-source-url=$URL_TO_GET_SAML_ASSERTION \
    --credential-source-headers $HEADER_KEY=$HEADER_VALUE \
    --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \
    --output-file=/path/to/generated/config.json

These commands generate the configuration file in the specified output file.

Where the following variables need to be substituted:

  • $WORKFORCE_POOL_ID: The workforce pool ID.
  • $PROVIDER_ID: The provider ID.
  • $URL_TO_GET_SAML_ASSERTION: The URL of the local server endpoint.
  • $HEADER_KEY and $HEADER_VALUE: The additional header key/value pairs to pass along the GET request to $URL_TO_GET_SAML_ASSERTION, e.g. Metadata-Flavor=Google.
  • $WORKFORCE_POOL_USER_PROJECT: The project number associated with the workforce pools user project.

Using Executable-sourced workforce credentials with OIDC and SAML

Executable-sourced credentials For executable-sourced credentials, a local executable is used to retrieve the 3rd party token. The executable must handle providing a valid, unexpired OIDC ID token or SAML assertion in JSON format to stdout.

To use executable-sourced credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable must be set to 1.

To generate an executable-sourced workforce identity configuration, run the following command:

# Generate a configuration file for executable-sourced credentials.
gcloud iam workforce-pools create-cred-config \
    locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \
    --subject-token-type=$SUBJECT_TOKEN_TYPE \
    # The absolute path for the program, including arguments.
    # e.g. --executable-command="/path/to/command --foo=bar"
    --executable-command=$EXECUTABLE_COMMAND \
    # Optional argument for the executable timeout. Defaults to 30s.
    # --executable-timeout-millis=$EXECUTABLE_TIMEOUT \
    # Optional argument for the absolute path to the executable output file.
    # See below on how this argument impacts the library behaviour.
    # --executable-output-file=$EXECUTABLE_OUTPUT_FILE \
    --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \
    --output-file /path/to/generated/config.json

Where the following variables need to be substituted:

  • $WORKFORCE_POOL_ID: The workforce pool ID.
  • $PROVIDER_ID: The provider ID.
  • $SUBJECT_TOKEN_TYPE: The subject token type.
  • $EXECUTABLE_COMMAND: The full command to run, including arguments. Must be an absolute path to the program.
  • $WORKFORCE_POOL_USER_PROJECT: The project number associated with the workforce pools user project.

The --executable-timeout-millis flag is optional. This is the duration for which the auth library will wait for the executable to finish, in milliseconds. Defaults to 30 seconds when not provided. The maximum allowed value is 2 minutes. The minimum is 5 seconds.

The --executable-output-file flag is optional. If provided, the file path must point to the 3rd party credential response generated by the executable. This is useful for caching the credentials. By specifying this path, the Auth libraries will first check for its existence before running the executable. By caching the executable JSON response to this file, it improves performance as it avoids the need to run the executable until the cached credentials in the output file are expired. The executable must handle writing to this file - the auth libraries will only attempt to read from this location. The format of contents in the file should match the JSON format expected by the executable shown below.

To retrieve the 3rd party token, the library will call the executable using the command specified. The executable's output must adhere to the response format specified below. It must output the response to stdout.

Refer to the using executable-sourced credentials with Workload Identity Federation above for the executable response specification.

Security considerations

The following security practices are highly recommended:

  • Access to the script should be restricted as it will be displaying credentials to stdout. This ensures that rogue processes do not gain access to the script.
  • The configuration file should not be modifiable. Write access should be restricted to avoid processes modifying the executable command portion.

Given the complexity of using executable-sourced credentials, it is recommended to use the existing supported mechanisms (file-sourced/URL-sourced) for providing 3rd party credentials unless they do not meet your specific requirements.

You can now use the Auth library to call Google Cloud resources from an OIDC or SAML provider.

Accessing resources from an OIDC or SAML2.0 identity provider using a custom supplier

If you want to use OIDC or SAML2.0 that cannot be retrieved using methods supported natively by this library, a custom SubjectTokenSupplier implementation may be specified when creating an identity pool client. The supplier must return a valid, unexpired subject token when called by the GCP credential.

Note that the client does not cache the returned subject token, so caching logic should be implemented in the supplier to prevent multiple requests for the same resources.

class CustomSupplier implements SubjectTokenSupplier {
  async getSubjectToken(
    context: ExternalAccountSupplierContext
  ): Promise<string> {
    const audience = context.audience;
    const subjectTokenType = context.subjectTokenType;
    // Return a valid subject token for the requested audience and subject token type.
  }
}

const clientOptions = {
  audience: '//iam.googleapis.com/locations/global/workforcePools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID', // Set the GCP audience.
  subject_token_type: 'urn:ietf:params:oauth:token-type:id_token', // Set the subject token type.
  subject_token_supplier: new CustomSupplier() // Set the custom supplier.
}

const client = new CustomSupplier(clientOptions);

Where the audience is: //iam.googleapis.com/locations/global/workforcePools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID

Where the following variables need to be substituted:

  • WORKFORCE_POOL_ID: The worforce pool ID.
  • $PROVIDER_ID: The provider ID.

and the workforce pool user project is the project number associated with the workforce pools user project.

The values for audience, service account impersonation URL, and any other builder field can also be found by generating a credential configuration file with the gcloud CLI.

Using External Identities

External identities (AWS, Azure and OIDC-based providers) can be used with Application Default Credentials. In order to use external identities with Application Default Credentials, you need to generate the JSON credentials configuration file for your external identity as described above. Once generated, store the path to this file in the GOOGLE_APPLICATION_CREDENTIALS environment variable.

export GOOGLE_APPLICATION_CREDENTIALS=/path/to/config.json

The library can now automatically choose the right type of client and initialize credentials from the context provided in the configuration file.

async function main() {
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/cloud-platform'
  });
  const client = await auth.getClient();
  const projectId = await auth.getProjectId();
  // List all buckets in a project.
  const url = `https://storage.googleapis.com/storage/v1/b?project=${projectId}`;
  const res = await client.request({ url });
  console.log(res.data);
}

When using external identities with Application Default Credentials in Node.js, the roles/browser role needs to be granted to the service account. The Cloud Resource Manager API should also be enabled on the project. This is needed since the library will try to auto-discover the project ID from the current environment using the impersonated credential. To avoid this requirement, the project ID can be explicitly specified on 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` to the service account
  // or enable Cloud Resource Manager API on the project.
  projectId: 'CLOUD_RESOURCE_PROJECT_ID',
});

You can also explicitly initialize external account clients using the generated configuration file.

const {ExternalAccountClient} = require('google-auth-library');
const jsonConfig = require('/path/to/config.json');

async function main() {
  const client = ExternalAccountClient.fromJSON(jsonConfig);
  client.scopes = ['https://www.googleapis.com/auth/cloud-platform'];
  // List all buckets in a project.
  const url = `https://storage.googleapis.com/storage/v1/b?project=${projectId}`;
  const res = await client.request({url});
  console.log(res.data);
}

Security Considerations

Note that this library does not perform any validation on the token_url, token_info_url, or service_account_impersonation_url fields of the credential configuration. It is not recommended to use a credential configuration that you did not generate with the gcloud CLI unless you verify that the URL fields point to a googleapis.com domain.

Working with ID Tokens

Fetching ID Tokens

If your application is running on Cloud Run or Cloud Functions, or using Cloud Identity-Aware Proxy (IAP), you will need to fetch an ID token to access your application. For this, use the method getIdTokenClient on the GoogleAuth client.

For invoking Cloud Run services, your service account will need the Cloud Run Invoker IAM permission.

For invoking Cloud Functions, your service account will need the Function Invoker IAM permission.

// Make a request to a protected Cloud Run service.
const {GoogleAuth} = require('google-auth-library');

async function main() {
  const url = 'https://cloud-run-1234-uc.a.run.app';
  const auth = new GoogleAuth();
  const client = await auth.getIdTokenClient(url);
  const res = await client.request({url});
  console.log(res.data);
}

main().catch(console.error);

A complete example can be found in samples/idtokens-serverless.js.

For invoking Cloud Identity-Aware Proxy, you will need to pass the Client ID used when you set up your protected resource as the target audience.

// Make a request to a protected Cloud Identity-Aware Proxy (IAP) resource
const {GoogleAuth} = require('google-auth-library');

async function main()
  const targetAudience = 'iap-client-id';
  const url = 'https://iap-url.com';
  const auth = new GoogleAuth();
  const client = await auth.getIdTokenClient(targetAudience);
  const res = await client.request({url});
  console.log(res.data);
}

main().catch(console.error);

A complete example can be found in samples/idtokens-iap.js.

Verifying ID Tokens

If you've secured your IAP app with signed headers, you can use this library to verify the IAP header:

const {OAuth2Client} = require('google-auth-library');
// Expected audience for App Engine.
const expectedAudience = `/projects/your-project-number/apps/your-project-id`;
// IAP issuer
const issuers = ['https://cloud.google.com/iap'];
// Verify the token. OAuth2Client throws an Error if verification fails
const oAuth2Client = new OAuth2Client();
const response = await oAuth2Client.getIapCerts();
const ticket = await oAuth2Client.verifySignedJwtWithCertsAsync(
  idToken,
  response.pubkeys,
  expectedAudience,
  issuers
);

// Print out the info contained in the IAP ID token
console.log(ticket)

A complete example can be found in samples/verifyIdToken-iap.js.

Impersonated Credentials Client

Google Cloud Impersonated credentials used for Creating short-lived service account credentials.

Provides authentication for applications where local credentials impersonates a remote service account using IAM Credentials API.

An Impersonated Credentials Client is instantiated with a sourceClient. This client should use credentials that have the "Service Account Token Creator" role (roles/iam.serviceAccountTokenCreator), and should authenticate with the https://www.googleapis.com/auth/cloud-platform, or https://www.googleapis.com/auth/iam scopes.

sourceClient is used by the Impersonated Credentials Client to impersonate a target service account with a specified set of scopes.

Sample Usage

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.Authorization`.

  // Use impersonated credentials:
  const url = 'https://www.googleapis.com/storage/v1/b?project=anotherProjectID'
  const resp = await targetClient.request({ 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();

Downscoped Client

Downscoping with Credential Access Boundaries is used to restrict the Identity and Access Management (IAM) permissions that a short-lived credential can use.

The DownscopedClient class can be used to produce a downscoped access token from a CredentialAccessBoundary and a source credential. The Credential Access Boundary specifies which resources the newly created credential can access, as well as an upper bound on the permissions that are available on each resource. Using downscoped credentials ensures tokens in flight always have the least privileges, e.g. Principle of Least Privilege.

Notice: Only Cloud Storage supports Credential Access Boundaries for now.

Sample Usage

There are two entities needed to

changelog

Changelog

npm history

9.15.0 (2024-11-01)

Features

9.14.2 (2024-10-09)

Bug Fixes

9.14.1 (2024-08-30)

Performance Improvements

  • GoogleAuth: Improve Client Creation From Files/Streams Perf (#1856) (85d9d6f)

9.14.0 (2024-08-19)

Features

Bug Fixes

  • deps: Update dependency @googleapis/iam to v21 (#1847) (e9459f3)

9.13.0 (2024-07-29)

Features

  • Group Concurrent Access Token Requests for Base External Clients (#1840) (0e08fc5)

9.12.0 (2024-07-26)

Features

Bug Fixes

  • deps: Update dependency @googleapis/iam to v19 (#1823) (b070ffb)
  • deps: Update dependency @googleapis/iam to v20 (#1832) (e31a831)

9.11.0 (2024-06-01)

Features

  • Adding support of client authentication method. (#1814) (4a14e8c)

9.10.0 (2024-05-10)

Features

  • Implement UserRefreshClient#fetchIdToken (#1811) (ae8bc54)

Bug Fixes

  • deps: Update dependency @googleapis/iam to v16 (#1803) (40406a0)
  • deps: Update dependency @googleapis/iam to v17 (#1808) (4d67f07)
  • deps: Update dependency @googleapis/iam to v18 (#1809) (b2b9676)

9.9.0 (2024-04-18)

Features

  • Adds suppliers for custom subject token and AWS credentials (#1795) (c680b5d)

9.8.0 (2024-04-12)

Features

Bug Fixes

9.7.0 (2024-03-12)

Features

Bug Fixes

  • deps: Update dependency @googleapis/iam to v15 (#1772) (f45f975)
  • Making aws request signer get a new session token each time security credentials are requested. (#1765) (6a6e496)

9.6.3 (2024-02-06)

Bug Fixes

  • Always sign with scopes on Non-Default Universes (#1752) (f3d3a03)

9.6.2 (2024-02-02)

Bug Fixes

9.6.1 (2024-02-01)

Bug Fixes

9.6.0 (2024-01-29)

Features

  • Open More Endpoints for Customization (#1721) (effbf87)
  • Use self-signed JWTs when non-default Universe Domains (#1722) (7e9876e)

Bug Fixes

  • Revert Missing WORKFORCE_AUDIENCE_PATTERN (#1740) (422de68)

9.5.0 (2024-01-25)

Features

Bug Fixes

9.4.2 (2024-01-04)

Bug Fixes

9.4.1 (2023-12-01)

Bug Fixes

  • Support 404 When GaxiosError != GaxiosError (#1707) (704674f)

9.4.0 (2023-11-30)

Features

9.3.0 (2023-11-29)

Features

Bug Fixes

9.2.0 (2023-10-26)

Features

Bug Fixes

9.1.0 (2023-10-02)

Features

Bug Fixes

  • deps: Update dependency @google-cloud/storage to v7 (#1629) (8075b6f)
  • deps: Update dependency @googleapis/iam to v11 (#1622) (03c0ac9)
  • deps: Update dependency google-auth-library to v9 (#1618) (1873fef)
  • deps: Update dependency puppeteer to v21 (#1627) (dd04fbd)
  • Workforce Audience Pattern (#1654) (77eeaed)

9.0.0 (2023-07-20)

⚠ BREAKING CHANGES

  • deps: upgrade node-gtoken to 7.0.0 (#1590)
  • make transporter attribute type more generic (#1406)
  • migrate to Node 14 (#1582)
  • remove arrify and fast-text-encoding (#1583)

Features

  • Make transporter attribute type more generic (#1406) (dfac525)

Bug Fixes

  • deps: Update dependency @googleapis/iam to v10 (#1588) (f95a153)

Build System

Miscellaneous Chores

8.9.0 (2023-06-29)

Features

  • Adds universe_domain field to base external client (#1548) (7412d7c)
  • Utilize gcp-metadata's GCP Residency Check (#1513) (43377ac)

Bug Fixes

8.8.0 (2023-04-25)

Features

  • Add External Account Authorized User client type (#1530) (06d4ef3)
  • Document External Account Authorized User Credentials (#1540) (c6138be)

Bug Fixes

  • deps: Update gcp-metadata to v5.2.0 (#1502) (2562d11)
  • deps: Update dependency @googleapis/iam to v4 (#1482) (00d6135)
  • deps: Update dependency @googleapis/iam to v5 (#1526) (a1f9835)
  • deps: Update dependency @googleapis/iam to v6 (#1536) (86a4de8)
  • deps: Update dependency @googleapis/iam to v7 (#1538) (fdb67dc)
  • Do not call metadata server if security creds and region are retrievable through environment vars (#1493) (d4de941)
  • Removing 3pi config URL validation (#1517) (a278d19)
  • Removing aws url validation (#1531) (f4d9335)

8.7.0 (2022-11-08)

Features

  • Introduce environment variable for quota project (#1478) (8706abc)

Bug Fixes

  • deps: Update dependency puppeteer to v19 (#1476) (86b258d)
  • Validate url domain for aws metadata urls (#1484) (6dc4e58)

8.6.0 (2022-10-06)

Features

8.5.2 (2022-09-22)

Bug Fixes

8.5.1 (2022-08-31)

Bug Fixes

8.5.0 (2022-08-31)

Features

  • Support Not Requiring projectId When Not Required (#1448) (b37489b)

Bug Fixes

8.4.0 (2022-08-23)

Features

  • adding configurable token lifespan support (#1441) (178e3b8)

Bug Fixes

8.3.0 (2022-08-19)

Features

  • Add generateIdToken support for Impersonated Clients (#1439) (4ace981)

8.2.0 (2022-08-11)

Features

8.1.1 (2022-07-08)

Bug Fixes

  • deps: update dependency puppeteer to v15 (#1424) (1462f2c)

8.1.0 (2022-06-30)

Features

8.0.3 (2022-06-17)

Bug Fixes

  • deps: update dependency @googleapis/iam to v3 (#1421) (0dc8857)

8.0.2 (2022-04-27)

Bug Fixes

  • Fixing Implementation of GoogleAuth.sign() for external account credentials (#1397) (b0ddb75)

8.0.1 (2022-04-22)

Bug Fixes

  • deps: update dependency gaxios to v5 (#1398) (cbd7d4f)
  • deps: update dependency google-auth-library to v8 (#1399) (9a8be63)

8.0.0 (2022-04-20)

⚠ BREAKING CHANGES

  • Set Node v12 to minimum supported version & Upgrade TypeScript (#1392)
  • remove deprecated DeprecatedGetClientOptions (#1393)

Code Refactoring

  • remove deprecated DeprecatedGetClientOptions (#1393) (9c02941)

Build System

  • Set Node v12 to minimum supported version & Upgrade TypeScript (#1392) (b7bcedb)

7.14.1 (2022-03-09)

Bug Fixes

7.14.0 (2022-02-22)

Features

  • Add AWS Session Token to Metadata Requests (#1363) (9ea3e98)

Bug Fixes

  • Rename auth to authClient & Use Generics for AuthClient (#1371) (8373000)

7.13.0 (2022-02-17)

Features

  • Support instantiating GoogleAuth with an AuthClient (#1364) (8839b5b)

7.12.0 (2022-02-09)

Features

7.11.0 (2021-12-15)

Features

  • adds README, samples and integration tests for downscoping with CAB (#1311) (4549116)

7.10.4 (2021-12-13)

Bug Fixes

  • deps: update dependency puppeteer to v13 (#1334) (e05548d)

7.10.3 (2021-11-29)

Bug Fixes

  • deps: update dependency puppeteer to v12 (#1325) (110ddc2)

7.10.2 (2021-11-03)

Bug Fixes

  • deps: update dependency puppeteer to v11 (#1312) (b3ba9ac)

7.10.1 (2021-10-14)

Bug Fixes

  • security: explicitly update keypair dependency (94401a6)

7.10.0 (2021-09-28)

Features

7.9.2 (2021-09-16)

Bug Fixes

  • deps: update dependency @googleapis/iam to v2 (#1253) (59b8243)

7.9.1 (2021-09-02)

Bug Fixes

7.9.0 (2021-09-02)

Features

  • wire up implementation of DownscopedClient. (#1232) (baa1318)

7.8.0 (2021-08-30)

Features

  • use self-signed JWTs if alwaysUseJWTAccessWithScope is true (#1196) (ad3f652)

7.7.0 (2021-08-27)

Features

  • add refreshHandler callback to OAuth 2.0 client to handle token refresh (#1213) (2fcab77)

7.6.2 (2021-08-17)

Bug Fixes

  • validate token_url and service_account_impersonation_url (#1229) (0360bb7)

7.6.1 (2021-08-13)

Bug Fixes

  • use updated variable name for self-signed JWTs (#1233) (ef41fe5)

7.6.0 (2021-08-10)

Features

  • add GoogleAuth.sign() support to external account client (#1227) (1ca3b73)

7.5.0 (2021-08-04)

Features

  • Adds support for STS response not returning expires_in field. (#1216) (24bb456)

7.4.1 (2021-07-29)

Bug Fixes

  • downscoped-client: bug fixes for downscoped client implementation. (#1219) (4fbe67e)

7.4.0 (2021-07-29)

Features

  • impersonated: add impersonated credentials auth (#1207) (ab1cd31)

7.3.0 (2021-07-02)

Features

  • add useJWTAccessWithScope and defaultServicePath variable (#1204) (79e100e)

7.2.0 (2021-06-30)

Features

  • Implement DownscopedClient#getAccessToken() and unit test (#1201) (faa6677)

7.1.2 (2021-06-10)

Bug Fixes

7.1.1 (2021-06-02)

Bug Fixes

  • deps: update dependency puppeteer to v10 (#1182) (003e3ee)

7.1.0 (2021-05-21)

Features

7.0.4 (2021-04-06)

Bug Fixes

  • do not suppress external project ID determination errors (#1153) (6c1c91d)

7.0.3 (2021-03-23)

Bug Fixes

  • support AWS_DEFAULT_REGION for determining AWS region (#1149) (9ae2d30)

7.0.2 (2021-02-10)

Bug Fixes

  • expose BaseExternalAccountClient and BaseExternalAccountClientOptions (#1142) (1d62c04)

7.0.1 (2021-02-09)

Bug Fixes

  • deps: update dependency google-auth-library to v7 (#1140) (9c717f7)

7.0.0 (2021-02-08)

⚠ BREAKING CHANGES

  • integrates external_accounts with GoogleAuth and ADC (#1052)
  • workload identity federation support (#1131)

Features

  • adds service account impersonation to ExternalAccountClient (#1041) (997f124)
  • adds text/json credential_source support to IdentityPoolClients (#1059) (997f124)
  • defines ExternalAccountClient used to instantiate external account clients (#1050) (997f124)
  • defines IdentityPoolClient used for K8s and Azure workloads (#1042) (997f124)
  • defines ExternalAccountClient abstract class for external_account credentials (#1030) (997f124)
  • get AWS region from environment variable (#1067) (997f124)
  • implements AWS signature version 4 for signing requests (#1047) (997f124)
  • implements the OAuth token exchange spec based on rfc8693 (#1026) (997f124)
  • integrates external_accounts with GoogleAuth and ADC (#1052) (997f124)
  • workload identity federation support (#1131) (997f124)

Bug Fixes

6.1.6 (2021-01-27)

Bug Fixes

  • call addSharedMetadataHeaders even when token has not expired (#1116) (aad043d)

6.1.5 (2021-01-22)

Bug Fixes

6.1.4 (2020-12-22)

Bug Fixes

  • move accessToken to headers instead of parameter (#1108) (67b0cc3)

6.1.3 (2020-10-22)

Bug Fixes

6.1.2 (2020-10-19)

Bug Fixes

  • update gcp-metadata to catch a json-bigint security fix (#1078) (125fe09)

6.1.1 (2020-10-06)

Bug Fixes

6.1.0 (2020-09-22)

Features

6.0.8 (2020-08-13)

Bug Fixes

  • deps: roll back dependency google-auth-library to ^6.0.6 (#1033) (eb54ee9)

6.0.7 (2020-08-11)

Bug Fixes

  • migrate token info API to not pass token in query string (#991) (a7e5701)

6.0.6 (2020-07-30)

Bug Fixes

  • types: include scope in credentials type (#1007) (a2b7d23)

6.0.5 (2020-07-13)

Bug Fixes

  • deps: update dependency lru-cache to v6 (#995) (3c07566)

6.0.4 (2020-07-09)

Bug Fixes

6.0.3 (2020-07-06)

Bug Fixes

  • deps: update dependency puppeteer to v5 (#986) (7cfe6f2)

6.0.2 (2020-06-16)

Bug Fixes

  • deps: update dependency puppeteer to v4 (#976) (9ddfb9b)
  • tsc: audience property is not mandatory on verifyIdToken (#972) (17a7e24)
  • types: add locale property to idtoken (#974) (ebf9bed), closes #973

6.0.1 (2020-05-21)

Bug Fixes

6.0.0 (2020-03-26)

⚠ BREAKING CHANGES

  • typescript@3.7.x introduced some breaking changes in generated code.
  • require node 10 in engines field (#926)
  • remove deprecated methods (#906)

Features

Bug Fixes

Build System

Miscellaneous Chores

5.10.1 (2020-02-25)

Bug Fixes

  • if GCF environment detected, increase library timeout (#899) (2577ff2)

5.10.0 (2020-02-20)

Features

  • support for verifying ES256 and retrieving IAP public keys (#887) (a98e386)

Bug Fixes

5.9.2 (2020-01-28)

Bug Fixes

  • populate credentials.refresh_token if provided (#881) (63c4637)

5.9.1 (2020-01-16)

Bug Fixes

  • ensures GCE metadata sets email field for ID tokens (#874) (e45b73d)

5.9.0 (2020-01-14)

Features

  • add methods for fetching and using id tokens (#867) (8036f1a)
  • export LoginTicket and TokenPayload (#870) (539ea5e)

5.8.0 (2020-01-06)

Features

Bug Fixes

5.7.0 (2019-12-10)

Features

  • make x-goog-user-project work for additional auth clients (#848) (46af865)

5.6.1 (2019-12-05)

Bug Fixes

  • deps: pin TypeScript below 3.7.0 (#845) (a9c6e92)
  • docs: improve types and docs for generateCodeVerifierAsync (#840) (04dae9c)

5.6.0 (2019-12-02)

Features

  • populate x-goog-user-project for requestAsync (#837) (5a068fb)
  • set x-goog-user-project header, with quota_project from default credentials (#829) (3240d16)

Bug Fixes

  • deps: update dependency puppeteer to v2 (#821) (2c04117)
  • docs: add jsdoc-region-tag plugin (#826) (558677f)
  • expand on x-goog-user-project to handle auth.getClient() (#831) (3646b7f)
  • use quota_project_id field instead of quota_project (#832) (8933966)

5.5.1 (2019-10-22)

Bug Fixes

  • deps: update gaxios dependency (#817) (6730698)
  • don't append x-goog-api-client multiple times (#820) (a46b271)

5.5.0 (2019-10-14)

Features

  • refresh: add forceRefreshOnFailure flag for refreshing token on error (#790) (54cf477)

5.4.1 (2019-10-10)

Bug Fixes

  • deps: updats to gcp-metadata with debug option (#811) (744e3e8)

5.4.0 (2019-10-08)

Features

5.3.0 (2019-09-27)

Features

  • if token expires soon, force refresh (#794) (fecd4f4)

5.2.2 (2019-09-17)

Bug Fixes

  • deps: update to gcp-metadata and address envDetect performance issues (#787) (651b5d4)

5.2.1 (2019-09-06)

Bug Fixes

  • deps: nock@next has types that work with our libraries (#783) (a253709)
  • docs: fix variable name in README.md (#782) (d8c70b9)

5.2.0 (2019-08-09)

Features

  • populate x-goog-api-client header for auth (#772) (526dcf6)

5.1.2 (2019-08-05)

Bug Fixes

5.1.1 (2019-07-29)

Bug Fixes

  • deps: update dependency google-auth-library to v5 (#759) (e32a12b)

5.1.0 (2019-07-24)

Features

  • types: expose ProjectIdCallback interface (#753) (5577f0d)

5.0.0 (2019-07-23)

⚠ BREAKING CHANGES

  • getOptions() no longer accepts GoogleAuthOptions (#749)

Code Refactoring

  • getOptions() no longer accepts GoogleAuthOptions (#749) (ba58e3b)

4.2.6 (2019-07-23)

Bug Fixes

  • use FUNCTION_TARGET to detect GCF 10 and above (#748) (ca17685)

4.2.5 (2019-06-26)

Bug Fixes

4.2.4 (2019-06-25)

Bug Fixes

  • only require fast-text-encoding when needed (#740) (04fcd77)

4.2.3 (2019-06-24)

Bug Fixes

  • feature detection to check for browser (#738) (83a5ba5)

4.2.2 (2019-06-18)

Bug Fixes

  • compute: correctly specify scopes when fetching token (#735) (4803e3c)

4.2.1 (2019-06-14)

Bug Fixes

4.2.0 (2019-06-05)

Bug Fixes

Features

  • make both crypto implementations support sign (#727) (e445fb3)

4.1.0 (2019-05-29)

Bug Fixes

  • deps: update dependency google-auth-library to v4 (#705) (2b13344)

Features

4.0.0 (2019-05-08)

Bug Fixes

  • deps: update dependency arrify to v2 (#684) (1757ee2)
  • deps: update dependency gaxios to v2 (#681) (770ad2f)
  • deps: update dependency gcp-metadata to v2 (#701) (be20528)
  • deps: update dependency gtoken to v3 (#702) (2c538e5)
  • re-throw original exception and preserve message in compute client (#668) (dffd1cc)
  • surface original stack trace and message with errors (#651) (8fb65eb)
  • throw on missing refresh token in all cases (#670) (0a02946)
  • throw when adc cannot acquire a projectId (#658) (ba48164)
  • deps: update dependency semver to v6 (#655) (ec56c88)

Build System

Features

  • support scopes on compute credentials (#642) (1811b7f)

BREAKING CHANGES

  • upgrade engines field to >=8.10.0 (#686)

v3.1.2

03-22-2019 15:38 PDT

Implementation Changes

  • fix: getCredential(): load credentials with getClient() (#648)

Internal / Testing Changes

  • chore: publish to npm using wombat (#645)

v3.1.1

03-18-2019 08:32 PDT

Bug Fixes

  • fix: Avoid loading fast-text-encoding if not in browser environment (#627)

Dependencies

  • fix(deps): update dependency gcp-metadata to v1 (#632)

Documentation

  • docs: update links in contrib guide (#630)

Internal / Testing Changes

  • build: use per-repo publish token (#641)
  • build: Add docuploader credentials to node publish jobs (#639)
  • build: use node10 to run samples-test, system-test etc (#638)
  • build: update release configuration
  • chore(deps): update dependency @types/lru-cache to v5 (#635)
  • chore(deps): update dependency mocha to v6
  • chore: fix lint (#631)
  • build: use linkinator for docs test (#628)
  • chore(deps): update dependency @types/tmp to ^0.0.34 (#629)
  • build: create docs test npm scripts (#625)
  • build: test using @grpc/grpc-js in CI (#624)

v3.1.0

02-08-2019 08:29 PST

Bug fixes

  • fix: use key file when fetching project id (#618)
  • fix: Throw error if there is no refresh token despite the necessity of refreshing (#605)

New Features

  • feat: allow passing constructor options to getClient (#611)

Documentation

  • docs: update contributing path in README (#621)
  • chore: move CONTRIBUTING.md to root (#619)
  • docs: add lint/fix example to contributing guide (#615)
  • docs: use the People API for samples (#609)

Internal / Testing Changes

  • chore(deps): update dependency typescript to ~3.3.0 (#612)
  • chore(deps): update dependency eslint-config-prettier to v4 (#604)
  • build: ignore googleapis.com in doc link check (#602)
  • chore(deps): update dependency karma to v4 (#603)

v3.0.1

01-16-2019 21:04 PST

Bug Fixes

  • fix(deps): upgrade to the latest gaxios (#596)

v3.0.0

01-16-2019 10:00 PST

Welcome to 3.0 🎉 This release has it all. New features, bug fixes, breaking changes, performance improvements - something for everyone! The biggest addition to this release is support for the browser via Webpack.

This release has breaking changes. This release has a few breaking changes. These changes are unlikely to affect most clients.

BREAKING: Migration from axios to gaxios

The 2.0 version of this library used the axios library for making HTTP requests. In the 3.0 release, this has been replaced by a mostly API compatible library gaxios. The new request library natively supports proxies, and comes with a smaller dependency chain. While this is mostly an implementation detail, the request method was directly exposed via the GoogleAuth.request and OAuth2Client.request methods. The gaxios library aims to provide an API compatible implementation of axios, but that can never be 100% promised. If you run into bugs or differences that cause issues - please do let us know.

BREAKING: generateCodeVerifier is now generateCodeVerifierAsync

The OAuth2Client.generateCodeVerifier method has been replaced by the OAuth2Client.generateCodeVerifierAsync method. It has changed from a synchronous method to an asynchronous method to support async browser crypto APIs required for Webpack support.

BREAKING: verifySignedJwtWithCerts is now verifySignedJwtWithCertsAsync

The OAuth2Client.verifySignedJwtWithCerts method has been replaced by the OAuth2Client.verifySignedJwtWithCertsAsync method. It has changed from a synchronous method to an asynchronous method to support async browser crypto APIs required for Webpack support.

New Features

  • feat: make it webpackable (#371)

Bug Fixes

  • fix: accept lowercase env vars (#578)

Dependencies

  • chore(deps): update gtoken (#592)
  • fix(deps): upgrade to gcp-metadata v0.9.3 (#586)

Documentation

  • docs: update bug report link (#585)
  • docs: clarify access and refresh token docs (#577)

Internal / Testing Changes

  • refactor(deps): use gaxios for HTTP requests instead of axios (#593)
  • fix: some browser fixes (#590)
  • chore(deps): update dependency ts-loader to v5 (#588)
  • chore(deps): update dependency karma to v3 (#587)
  • build: check broken links in generated docs (#579)
  • chore(deps): drop unused dep on typedoc (#583)
  • build: add browser test running on Kokoro (#584)
  • test: improve samples and add tests (#576)

v2.0.2

12-16-2018 10:48 PST

Fixes

  • fix(types): export GCPEnv type (#569)
  • fix: use post for token revocation (#524)

Dependencies

  • fix(deps): update dependency lru-cache to v5 (#541)

Documentation

  • docs: add ref docs again (#553)
  • docs: clean up the readme (#554)

Internal / Testing Changes

  • chore(deps): update dependency @types/sinon to v7 (#568)
  • refactor: use execa for install tests, run eslint on samples (#559)
  • chore(build): inject yoshi automation key (#566)
  • chore: update nyc and eslint configs (#565)
  • chore: fix publish.sh permission +x (#563)
  • fix(build): fix Kokoro release script (#562)
  • build: add Kokoro configs for autorelease (#561)
  • chore: always nyc report before calling codecov (#557)
  • chore: nyc ignore build/test by default (#556)
  • chore(build): update the prettier and renovate config (#552)
  • chore: update license file (#551)
  • fix(build): fix system key decryption (#547)
  • chore(deps): update dependency typescript to ~3.2.0 (#546)
  • chore(deps): unpin sinon (#544)
  • refactor: drop non-required modules (#542)
  • chore: add synth.metadata (#537)
  • fix: Pin @types/sinon to last compatible version (#538)
  • chore(deps): update dependency gts to ^0.9.0 (#531)
  • chore: update eslintignore config (#530)
  • chore: drop contributors from multiple places (#528)
  • chore: use latest npm on Windows (#527)
  • chore: update CircleCI config (#523)
  • chore: include build in eslintignore (#516)

v2.0.1

Implementation Changes

  • fix: verifyIdToken will never return null (#488)
  • Update the url to application default credentials (#470)
  • Update omitted parameter 'hd' (#467)

Dependencies

  • chore(deps): update dependency nock to v10 (#501)
  • chore(deps): update dependency sinon to v7 (#502)
  • chore(deps): update dependency typescript to v3.1.3 (#503)
  • chore(deps): update dependency gh-pages to v2 (#499)
  • chore(deps): update dependency typedoc to ^0.13.0 (#497)

Documentation

  • docs: Remove code format from Application Default Credentials (#483)
  • docs: replace google/ with googleapis/ in URIs (#472)
  • Fix typo in readme (#469)
  • Update samples and docs for 2.0 (#459)

Internal / Testing Changes

  • chore: update issue templates (#509)
  • chore: remove old issue template (#507)
  • build: run tests on node11 (#506)
  • chore(build): drop hard rejection and update gts in the kitchen test (#504)
  • chores(build): do not collect sponge.xml from windows builds (#500)
  • chores(build): run codecov on continuous builds (#495)
  • chore: update new issue template (#494)
  • build: fix codecov uploading on Kokoro (#490)
  • test: move kitchen sink tests to system-test (#489)
  • Update kokoro config (#482)
  • fix: export additional typescript types (#479)
  • Don't publish sourcemaps (#478)
  • test: remove appveyor config (#477)
  • Enable prefer-const in the eslint config (#473)
  • Enable no-var in eslint (#471)
  • Update CI config (#468)
  • Retry npm install in CI (#465)
  • Update Kokoro config (#462)

v2.0.0

Well hello 2.0 🎉 This release has multiple breaking changes. It also has a lot of bug fixes.

Breaking Changes

Support for node.js 4.x and 9.x has been dropped

These versions of node.js are no longer supported.

The getRequestMetadata method has been deprecated

The getRequestMetadata method has been deprecated on the IAM, OAuth2, JWT, and JWTAccess classes. The getRequestHeaders method should be used instead. The methods have a subtle difference: the getRequestMetadata method returns an object with a headers property, which contains the authorization header. The getRequestHeaders method simply returns the headers.

Old code
const client = await auth.getClient();
const res = await client.getRequestMetadata();
const headers = res.headers;
New code
const client = await auth.getClient();
const headers = await client.getRequestHeaders();

The createScopedRequired method has been deprecated

The createScopedRequired method has been deprecated on multiple classes. The createScopedRequired and createScoped methods on the JWT class were largely in place to help inform clients when scopes were required in an application default credential scenario. Instead of checking if scopes are required after creating the client, instead scopes should just be passed either into the GoogleAuth.getClient method, or directly into the JWT constructor.

Old code
auth.getApplicationDefault(function(err, authClient) {
   if (err) {
     return callback(err);
   }
  if (authClient.createScopedRequired && authClient.createScopedRequired()) {
    authClient = authClient.createScoped([
      'https://www.googleapis.com/auth/cloud-platform'
    ]);
  }
  callback(null, authClient);
});
New code
const client = await auth.getClient({
  scopes: ['https://www.googleapis.com/auth/cloud-platform']
});

Deprecate refreshAccessToken

Note: refreshAccessToken is no longer deprecated.

getAccessToken, getRequestMetadata, and request methods will all refresh the token if needed automatically.

You should not need to invoke refreshAccessToken directly except in certain edge-cases.

Features

  • Set private_key_id in JWT access token header like other google auth libraries. (#450)

Bug Fixes

  • fix: support HTTPS proxies (#405)
  • fix: export missing interfaces (#437)
  • fix: Use new auth URIs (#434)
  • docs: Fix broken link (#423)
  • fix: surface file read streams (#413)
  • fix: prevent unhandled rejections by avoid .catch (#404)
  • fix: use gcp-metadata for compute credentials (#409)
  • Add Code of Conduct
  • fix: Warn when using user credentials from the Cloud SDK (#399)
  • fix: use Buffer.from instead of new Buffer (#400)
  • fix: Fix link format in README.md (#385)

Breaking changes

  • chore: deprecate getRequestMetadata (#414)
  • fix: deprecate the createScopedRequired methods (#410)
  • fix: drop support for node.js 4.x and 9.x (#417)
  • fix: deprecate the refreshAccessToken methods (#411)
  • fix: deprecate the getDefaultProjectId method (#402)
  • fix: drop support for node.js 4 (#401)

Build / Test changes

  • Run synth to make build tools consistent (#455)
  • Add a package.json for samples and cleanup README (#454)
  • chore(deps): update dependency typedoc to ^0.12.0 (#453)
  • chore: move examples => samples + synth (#448)
  • chore(deps): update dependency nyc to v13 (#452)
  • chore(deps): update dependency pify to v4 (#447)
  • chore(deps): update dependency assert-rejects to v1 (#446)
  • chore: ignore package-lock.json (#445)
  • chore: update renovate config (#442)
  • chore(deps): lock file maintenance (#443)
  • chore: remove greenkeeper badge (#440)
  • test: throw on deprecation
  • chore: add intelli-espower-loader for running tests (#430)
  • chore(deps): update dependency typescript to v3 (#432)
  • chore(deps): lock file maintenance (#431)
  • test: use strictEqual in tests (#425)
  • chore(deps): lock file maintenance (#428)
  • chore: Configure Renovate (#424)
  • chore: Update gts to the latest version 🚀 (#422)
  • chore: update gcp-metadata for isAvailable fix (#420)
  • refactor: use assert.reject in the tests (#415)
  • refactor: cleanup types for certificates (#412)
  • test: run tests with hard-rejection (#397)
  • cleanup: straighten nested try-catch (#394)
  • test: getDefaultProjectId should prefer config (#388)
  • chore(package): Update gts to the latest version 🚀 (#387)
  • chore(package): update sinon to version 6.0.0 (#386)

Upgrading to 1.x

The 1.x release includes a variety of bug fixes, new features, and breaking changes. Please take care, and see the release notes for a list of breaking changes, and the upgrade guide.