Gathering detailed insights and metrics for google-auth-library
Gathering detailed insights and metrics for google-auth-library
Gathering detailed insights and metrics for google-auth-library
Gathering detailed insights and metrics for google-auth-library
passport-google-verify-token
Google Token strategy for Passport, let's you validate the user token server side, usefull for mobile app Google authentication for example. The validation is done by the official Google Auth library for NodeJs.
strapi-google-auth
GoogleAuth helps you to easily create google authentication available for your users. It uses the official google-auth library to execute the actions.
passport-google-strategy
passport strategy that uses google-auth library to verify id token before logging in user
gtoken
Node.js Google Authentication Service Account Tokens
🔑 Google Auth Library for Node.js
npm install google-auth-library
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1,734 Stars
1,097 Commits
382 Forks
90 Watching
126 Branches
201 Contributors
Updated on 25 Nov 2024
TypeScript (98.83%)
JavaScript (1.08%)
Python (0.09%)
Cumulative downloads
Total Downloads
Last day
0%
2,414,035
Compared to previous day
Last week
3.2%
12,920,909
Compared to previous week
Last month
11%
53,837,128
Compared to previous month
Last year
50.2%
582,518,683
Compared to previous year
40
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:
1npm install google-auth-library
This library provides a variety of ways to authenticate to your Google services.
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.
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.
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
.
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.
1const {GoogleAuth} = require('google-auth-library'); 2 3/** 4* Instead of specifying the type of client you'd like to use (JWT, OAuth2, etc) 5* this library will automatically choose the right client based on the environment. 6*/ 7async function main() { 8 const auth = new GoogleAuth({ 9 scopes: 'https://www.googleapis.com/auth/cloud-platform' 10 }); 11 const client = await auth.getClient(); 12 const projectId = await auth.getProjectId(); 13 const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; 14 const res = await client.request({ url }); 15 console.log(res.data); 16} 17 18main().catch(console.error);
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.
Let's take a look at a complete example.
1const {OAuth2Client} = require('google-auth-library'); 2const http = require('http'); 3const url = require('url'); 4const open = require('open'); 5const destroyer = require('server-destroy'); 6 7// Download your OAuth2 configuration from the Google 8const keys = require('./oauth2.keys.json'); 9 10/** 11* Start by acquiring a pre-authenticated oAuth2 client. 12*/ 13async function main() { 14 const oAuth2Client = await getAuthenticatedClient(); 15 // Make a simple request to the People API using our pre-authenticated client. The `request()` method 16 // takes an GaxiosOptions object. Visit https://github.com/JustinBeckwith/gaxios. 17 const url = 'https://people.googleapis.com/v1/people/me?personFields=names'; 18 const res = await oAuth2Client.request({url}); 19 console.log(res.data); 20 21 // After acquiring an access_token, you may want to check on the audience, expiration, 22 // or original scopes requested. You can do that with the `getTokenInfo` method. 23 const tokenInfo = await oAuth2Client.getTokenInfo( 24 oAuth2Client.credentials.access_token 25 ); 26 console.log(tokenInfo); 27} 28 29/** 30* Create a new OAuth2Client, and go through the OAuth2 content 31* workflow. Return the full client to the callback. 32*/ 33function getAuthenticatedClient() { 34 return new Promise((resolve, reject) => { 35 // create an oAuth client to authorize the API call. Secrets are kept in a `keys.json` file, 36 // which should be downloaded from the Google Developers Console. 37 const oAuth2Client = new OAuth2Client( 38 keys.web.client_id, 39 keys.web.client_secret, 40 keys.web.redirect_uris[0] 41 ); 42 43 // Generate the url that will be used for the consent dialog. 44 const authorizeUrl = oAuth2Client.generateAuthUrl({ 45 access_type: 'offline', 46 scope: 'https://www.googleapis.com/auth/userinfo.profile', 47 }); 48 49 // Open an http server to accept the oauth callback. In this simple example, the 50 // only request to our webserver is to /oauth2callback?code=<code> 51 const server = http 52 .createServer(async (req, res) => { 53 try { 54 if (req.url.indexOf('/oauth2callback') > -1) { 55 // acquire the code from the querystring, and close the web server. 56 const qs = new url.URL(req.url, 'http://localhost:3000') 57 .searchParams; 58 const code = qs.get('code'); 59 console.log(`Code is ${code}`); 60 res.end('Authentication successful! Please return to the console.'); 61 server.destroy(); 62 63 // Now that we have the code, use that to acquire tokens. 64 const r = await oAuth2Client.getToken(code); 65 // Make sure to set the credentials on the OAuth2 client. 66 oAuth2Client.setCredentials(r.tokens); 67 console.info('Tokens acquired.'); 68 resolve(oAuth2Client); 69 } 70 } catch (e) { 71 reject(e); 72 } 73 }) 74 .listen(3000, () => { 75 // open the browser to the authorize url to start the workflow 76 open(authorizeUrl, {wait: false}).then(cp => cp.unref()); 77 }); 78 destroyer(server); 79 }); 80} 81 82main().catch(console.error);
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:
1const client = await auth.getClient(); 2 3client.on('tokens', (tokens) => { 4 if (tokens.refresh_token) { 5 // store the refresh_token in my database! 6 console.log(tokens.refresh_token); 7 } 8 console.log(tokens.access_token); 9}); 10 11const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; 12const res = await client.request({ url }); 13// The `tokens` event would now be raised if this was the first request
With the code returned, you can ask for an access token as shown below:
1const tokens = await oauth2Client.getToken(code);
2// Now tokens contains an access_token and an optional refresh_token. Save them.
3oauth2Client.setCredentials(tokens);
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
:
1// Generate the url that will be used for the consent dialog.
2const authorizeUrl = oAuth2Client.generateAuthUrl({
3 // To get a refresh token, you MUST set access_type to `offline`.
4 access_type: 'offline',
5 // set the appropriate scopes
6 scope: 'https://www.googleapis.com/auth/userinfo.profile',
7 // A refresh token is only returned the first time the user
8 // consents to providing access. For illustration purposes,
9 // setting the prompt to 'consent' will force this consent
10 // every time, forcing a refresh_token to be returned.
11 prompt: 'consent'
12});
access_token
informationAfter 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:
1// after acquiring an oAuth2Client... 2const tokenInfo = await oAuth2Client.getTokenInfo('my-access-token'); 3 4// take a look at the scopes originally provisioned for the access token 5console.log(tokenInfo.scopes);
This method will throw if the token is invalid.
An API key can be provided to the constructor:
1const client = new OAuth2Client({
2 apiKey: 'my-api-key'
3});
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:
1const auth = new GoogleAuth({
2 clientOptions: {
3 apiKey: 'my-api-key'
4 }
5})
API Key support varies by API.
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.
1const {JWT} = require('google-auth-library'); 2const keys = require('./jwt.keys.json'); 3 4async function main() { 5 const client = new JWT({ 6 email: keys.client_email, 7 key: keys.private_key, 8 scopes: ['https://www.googleapis.com/auth/cloud-platform'], 9 }); 10 const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`; 11 const res = await client.request({url}); 12 console.log(res.data); 13} 14 15main().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.
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:
1const {auth} = require('google-auth-library'); 2 3// load the environment variable with our keys 4const keysEnvVar = process.env['CREDS']; 5if (!keysEnvVar) { 6 throw new Error('The $CREDS environment variable was not found!'); 7} 8const keys = JSON.parse(keysEnvVar); 9 10async function main() { 11 // load the JWT or UserRefreshClient from the keys 12 const client = auth.fromJSON(keys); 13 client.scopes = ['https://www.googleapis.com/auth/cloud-platform']; 14 const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`; 15 const res = await client.request({url}); 16 console.log(res.data); 17} 18 19main().catch(console.error);
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.
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.
1const {auth, Compute} = require('google-auth-library'); 2 3async function main() { 4 const client = new Compute({ 5 // Specifying the service account email is optional. 6 serviceAccountEmail: 'my-service-account@example.com' 7 }); 8 const projectId = await auth.getProjectId(); 9 const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; 10 const res = await client.request({url}); 11 console.log(res.data); 12} 13 14main().catch(console.error);
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.
In order to access Google Cloud resources from Amazon Web Services (AWS), the following requirements are needed:
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:
1# Generate an AWS configuration file. 2gcloud iam workload-identity-pools create-cred-config \ 3 projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AWS_PROVIDER_ID \ 4 --service-account $SERVICE_ACCOUNT_EMAIL \ 5 --aws \ 6 --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.
In order to access Google Cloud resources from Amazon Web Services (AWS), the following requirements are needed:
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.
1import { AwsClient, AwsSecurityCredentials, AwsSecurityCredentialsSupplier, ExternalAccountSupplierContext } from 'google-auth-library'; 2import { fromNodeProviderChain } from '@aws-sdk/credential-providers'; 3import { Storage } from '@google-cloud/storage'; 4 5class AwsSupplier implements AwsSecurityCredentialsSupplier { 6 private readonly region: string 7 8 constructor(region: string) { 9 this.region = options.region; 10 } 11 12 async getAwsRegion(context: ExternalAccountSupplierContext): Promise<string> { 13 // Return the AWS region i.e. "us-east-2". 14 return this.region 15 } 16 17 async getAwsSecurityCredentials( 18 context: ExternalAccountSupplierContext 19 ): Promise<AwsSecurityCredentials> { 20 // Retrieve the AWS credentails. 21 const awsCredentialsProvider = fromNodeProviderChain(); 22 const awsCredentials = await awsCredentialsProvider(); 23 24 // Parse the AWS credentials into a AWS security credentials instance and 25 // return them. 26 const awsSecurityCredentials = { 27 accessKeyId: awsCredentials.accessKeyId, 28 secretAccessKey: awsCredentials.secretAccessKey, 29 token: awsCredentials.sessionToken 30 } 31 return awsSecurityCredentials; 32 } 33} 34 35const clientOptions = { 36 audience: '//iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID', // Set the GCP audience. 37 subject_token_type: 'urn:ietf:params:aws:token-type:aws4_request', // Set the subject token type. 38 aws_security_credentials_supplier: new AwsSupplier("AWS_REGION") // Set the custom supplier. 39} 40 41// Create a new Auth client and use it to create service client, i.e. storage. 42const authClient = new AwsClient(clientOptions); 43const 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.
In order to access Google Cloud resources from Microsoft Azure, the following requirements are needed:
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:
1# Generate an Azure configuration file. 2gcloud iam workload-identity-pools create-cred-config \ 3 projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AZURE_PROVIDER_ID \ 4 --service-account $SERVICE_ACCOUNT_EMAIL \ 5 --azure \ 6 --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.
In order to access Google Cloud resources from an identity provider that supports OpenID Connect (OIDC), the following requirements are needed:
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:
1# Generate an OIDC configuration file for file-sourced credentials. 2gcloud iam workload-identity-pools create-cred-config \ 3 projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$OIDC_PROVIDER_ID \ 4 --service-account $SERVICE_ACCOUNT_EMAIL \ 5 --credential-source-file $PATH_TO_OIDC_ID_TOKEN \ 6 # Optional arguments for file types. Default is "text": 7 # --credential-source-type "json" \ 8 # Optional argument for the field that contains the OIDC credential. 9 # This is required for json. 10 # --credential-source-field-name "id_token" \ 11 --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:
1# Generate an OIDC configuration file for URL-sourced credentials. 2gcloud iam workload-identity-pools create-cred-config \ 3 projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$OIDC_PROVIDER_ID \ 4 --service-account $SERVICE_ACCOUNT_EMAIL \ 5 --credential-source-url $URL_TO_GET_OIDC_TOKEN \ 6 --credential-source-headers $HEADER_KEY=$HEADER_VALUE \ 7 # Optional arguments for file types. Default is "text": 8 # --credential-source-type "json" \ 9 # Optional argument for the field that contains the OIDC credential. 10 # This is required for json. 11 # --credential-source-field-name "id_token" \ 12 --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
.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.
1class CustomSupplier implements SubjectTokenSupplier { 2 async getSubjectToken( 3 context: ExternalAccountSupplierContext 4 ): Promise<string> { 5 const audience = context.audience; 6 const subjectTokenType = context.subjectTokenType; 7 // Return a valid subject token for the requested audience and subject token type. 8 } 9} 10 11const clientOptions = { 12 audience: '//iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID', // Set the GCP audience. 13 subject_token_type: 'urn:ietf:params:oauth:token-type:id_token', // Set the subject token type. 14 subject_token_supplier: new CustomSupplier() // Set the custom supplier. 15} 16 17const 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.
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:
1gcloud auth application-default login --login-config=$LOGIN_CONFIG
Where the following variable needs to be substituted:
$LOGIN_CONFIG
: The login config file generated with the cloud console or
gcloud iam workforce-pools create-login-configThis 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.
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:
1# Generate a configuration file for executable-sourced credentials. 2gcloud iam workload-identity-pools create-cred-config \ 3 projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$PROVIDER_ID \ 4 --service-account=$SERVICE_ACCOUNT_EMAIL \ 5 --subject-token-type=$SUBJECT_TOKEN_TYPE \ 6 # The absolute path for the program, including arguments. 7 # e.g. --executable-command="/path/to/command --foo=bar" 8 --executable-command=$EXECUTABLE_COMMAND \ 9 # Optional argument for the executable timeout. Defaults to 30s. 10 # --executable-timeout-millis=$EXECUTABLE_TIMEOUT \ 11 # Optional argument for the absolute path to the executable output file. 12 # See below on how this argument impacts the library behaviour. 13 # --executable-output-file=$EXECUTABLE_OUTPUT_FILE \ 14 --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:
1{ 2 "version": 1, 3 "success": true, 4 "token_type": "urn:ietf:params:oauth:token-type:id_token", 5 "id_token": "HEADER.PAYLOAD.SIGNATURE", 6 "expiration_time": 1620499962 7}
A sample successful executable SAML response:
1{ 2 "version": 1, 3 "success": true, 4 "token_type": "urn:ietf:params:oauth:token-type:saml2", 5 "saml_response": "...", 6 "expiration_time": 1620499962 7}
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:
1{ 2 "version": 1, 3 "success": false, 4 "code": "401", 5 "message": "Caller not authorized." 6}
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.
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.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.
The following security practices are highly recommended:
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.
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):
1# Generate an AWS configuration file with configurable token lifetime. 2gcloud iam workload-identity-pools create-cred-config \ 3 projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$AWS_PROVIDER_ID \ 4 --service-account $SERVICE_ACCOUNT_EMAIL \ 5 --aws \ 6 --output-file /path/to/generated/config.json \ 7 --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 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.
In order to access Google Cloud resources from an identity provider that supports OpenID Connect (OIDC), the following requirements are needed:
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:
1# Generate an OIDC configuration file for file-sourced credentials. 2gcloud iam workforce-pools create-cred-config \ 3 locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ 4 --subject-token-type=urn:ietf:params:oauth:token-type:id_token \ 5 --credential-source-file=$PATH_TO_OIDC_ID_TOKEN \ 6 --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ 7 # Optional arguments for file types. Default is "text": 8 # --credential-source-type "json" \ 9 # Optional argument for the field that contains the OIDC credential. 10 # This is required for json. 11 # --credential-source-field-name "id_token" \ 12 --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:
1# Generate a SAML configuration file for file-sourced credentials. 2gcloud iam workforce-pools create-cred-config \ 3 locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ 4 --credential-source-file=$PATH_TO_SAML_ASSERTION \ 5 --subject-token-type=urn:ietf:params:oauth:token-type:saml2 \ 6 --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ 7 --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:
1# Generate an OIDC configuration file for URL-sourced credentials. 2gcloud iam workforce-pools create-cred-config \ 3 locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ 4 --subject-token-type=urn:ietf:params:oauth:token-type:id_token \ 5 --credential-source-url=$URL_TO_RETURN_OIDC_ID_TOKEN \ 6 --credential-source-headers $HEADER_KEY=$HEADER_VALUE \ 7 --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ 8 --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:
1# Generate a SAML configuration file for file-sourced credentials. 2gcloud iam workforce-pools create-cred-config \ 3 locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ 4 --subject-token-type=urn:ietf:params:oauth:token-type:saml2 \ 5 --credential-source-url=$URL_TO_GET_SAML_ASSERTION \ 6 --credential-source-headers $HEADER_KEY=$HEADER_VALUE \ 7 --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ 8 --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.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:
1# Generate a configuration file for executable-sourced credentials. 2gcloud iam workforce-pools create-cred-config \ 3 locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ 4 --subject-token-type=$SUBJECT_TOKEN_TYPE \ 5 # The absolute path for the program, including arguments. 6 # e.g. --executable-command="/path/to/command --foo=bar" 7 --executable-command=$EXECUTABLE_COMMAND \ 8 # Optional argument for the executable timeout. Defaults to 30s. 9 # --executable-timeout-millis=$EXECUTABLE_TIMEOUT \ 10 # Optional argument for the absolute path to the executable output file. 11 # See below on how this argument impacts the library behaviour. 12 # --executable-output-file=$EXECUTABLE_OUTPUT_FILE \ 13 --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ 14 --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.
The following security practices are highly recommended:
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.
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.
1class CustomSupplier implements SubjectTokenSupplier { 2 async getSubjectToken( 3 context: ExternalAccountSupplierContext 4 ): Promise<string> { 5 const audience = context.audience; 6 const subjectTokenType = context.subjectTokenType; 7 // Return a valid subject token for the requested audience and subject token type. 8 } 9} 10 11const clientOptions = { 12 audience: '//iam.googleapis.com/locations/global/workforcePools/$WORKLOAD_POOL_ID/providers/$PROVIDER_ID', // Set the GCP audience. 13 subject_token_type: 'urn:ietf:params:oauth:token-type:id_token', // Set the subject token type. 14 subject_token_supplier: new CustomSupplier() // Set the custom supplier. 15} 16 17const 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.
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.
1export 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.
1async function main() { 2 const auth = new GoogleAuth({ 3 scopes: 'https://www.googleapis.com/auth/cloud-platform' 4 }); 5 const client = await auth.getClient(); 6 const projectId = await auth.getProjectId(); 7 // List all buckets in a project. 8 const url = `https://storage.googleapis.com/storage/v1/b?project=${projectId}`; 9 const res = await client.request({ url }); 10 console.log(res.data); 11}
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.
1const auth = new GoogleAuth({
2 scopes: 'https://www.googleapis.com/auth/cloud-platform',
3 // Pass the project ID explicitly to avoid the need to grant `roles/browser` to the service account
4 // or enable Cloud Resource Manager API on the project.
5 projectId: 'CLOUD_RESOURCE_PROJECT_ID',
6});
You can also explicitly initialize external account clients using the generated configuration file.
1const {ExternalAccountClient} = require('google-auth-library'); 2const jsonConfig = require('/path/to/config.json'); 3 4async function main() { 5 const client = ExternalAccountClient.fromJSON(jsonConfig); 6 client.scopes = ['https://www.googleapis.com/auth/cloud-platform']; 7 // List all buckets in a project. 8 const url = `https://storage.googleapis.com/storage/v1/b?project=${projectId}`; 9 const res = await client.request({url}); 10 console.log(res.data); 11}
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.
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.
1// Make a request to a protected Cloud Run service. 2const {GoogleAuth} = require('google-auth-library'); 3 4async function main() { 5 const url = 'https://cloud-run-1234-uc.a.run.app'; 6 const auth = new GoogleAuth(); 7 const client = await auth.getIdTokenClient(url); 8 const res = await client.request({url}); 9 console.log(res.data); 10} 11 12main().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.
1// Make a request to a protected Cloud Identity-Aware Proxy (IAP) resource 2const {GoogleAuth} = require('google-auth-library'); 3 4async function main() 5 const targetAudience = 'iap-client-id'; 6 const url = 'https://iap-url.com'; 7 const auth = new GoogleAuth(); 8 const client = await auth.getIdTokenClient(targetAudience); 9 const res = await client.request({url}); 10 console.log(res.data); 11} 12 13main().catch(console.error);
A complete example can be found in samples/idtokens-iap.js
.
If you've secured your IAP app with signed headers, you can use this library to verify the IAP header:
1const {OAuth2Client} = require('google-auth-library'); 2// Expected audience for App Engine. 3const expectedAudience = `/projects/your-project-number/apps/your-project-id`; 4// IAP issuer 5const issuers = ['https://cloud.google.com/iap']; 6// Verify the token. OAuth2Client throws an Error if verification fails 7const oAuth2Client = new OAuth2Client(); 8const response = await oAuth2Client.getIapCerts(); 9const ticket = await oAuth2Client.verifySignedJwtWithCertsAsync( 10 idToken, 11 response.pubkeys, 12 expectedAudience, 13 issuers 14); 15 16// Print out the info contained in the IAP ID token 17console.log(ticket)
A complete example can be found in samples/verifyIdToken-iap.js
.
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.
1const { GoogleAuth, Impersonated } = require('google-auth-library'); 2const { SecretManagerServiceClient } = require('@google-cloud/secret-manager'); 3 4async function main() { 5 6 // Acquire source credentials: 7 const auth = new GoogleAuth(); 8 const client = await auth.getClient(); 9 10 // Impersonate new credentials: 11 let targetClient = new Impersonated({ 12 sourceClient: client, 13 targetPrincipal: 'impersonated-account@projectID.iam.gserviceaccount.com', 14 lifetime: 30, 15 delegates: [], 16 targetScopes: ['https://www.googleapis.com/auth/cloud-platform'] 17 }); 18 19 // Get impersonated credentials: 20 const authHeaders = await targetClient.getRequestHeaders(); 21 // Do something with `authHeaders.Authorization`. 22 23 // Use impersonated credentials: 24 const url = 'https://www.googleapis.com/storage/v1/b?project=anotherProjectID' 25 const resp = await targetClient.request({ url }); 26 for (const bucket of resp.data.items) { 27 console.log(bucket.name); 28 } 29 30 // Use impersonated credentials with google-cloud client library 31 // Note: this works only with certain cloud client libraries utilizing gRPC 32 // e.g., SecretManager, KMS, AIPlatform 33 // will not currently work with libraries using REST, e.g., Storage, Compute 34 const smClient = new SecretManagerServiceClient({ 35 projectId: anotherProjectID, 36 auth: { 37 getClient: () => targetClient, 38 }, 39 }); 40 const secretName = 'projects/anotherProjectNumber/secrets/someProjectName/versions/1'; 41 const [accessResponse] = await smClient.accessSecretVersion({ 42 name: secretName, 43 }); 44 45 const responsePayload = accessResponse.payload.data.toString('utf8'); 46 // Do something with the secret contained in `responsePayload`. 47}; 48 49main();
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.
There are two entities needed to generate and use credentials generated from Downscoped Client with Credential Access Boundaries.
1const {GoogleAuth, DownscopedClient} = require('google-auth-library');
2// Define CAB rules which will restrict the downscoped token to have readonly
3// access to objects starting with "customer-a" in bucket "bucket_name".
4const cabRules = {
5 accessBoundary: {
6 accessBoundaryRules: [
7 {
8 availableResource: `//storage.googleapis.com/projects/_/buckets/bucket_name`,
9 availablePermissions: ['inRole:roles/storage.objectViewer'],
10 availabilityCondition: {
11 expression:
12 `resource.name.startsWith('projects/_/buckets/` +
13 `bucket_name/objects/customer-a)`
14 }
15 },
16 ],
17 },
18};
19
20// This will use ADC to get the credentials used for the downscoped client.
21const googleAuth = new GoogleAuth({
22 scopes: ['https://www.googleapis.com/auth/cloud-platform']
23});
24
25// Obtain an authenticated client via ADC.
26const client = await googleAuth.getClient();
27
28// Use the client to create a DownscopedClient.
29const cabClient = new DownscopedClient(client, cab);
30
31// Refresh the tokens.
32const refreshedAccessToken = await cabClient.getAccessToken();
33
34// This will need to be passed to the token consumer.
35access_token = refreshedAccessToken.token;
36expiry_date = refreshedAccessToken.expirationTime;
A token broker can be set up on a server in a private network. Various workloads (token consumers) in the same network will send authenticated requests to that broker for downscoped tokens to access or modify specific google cloud storage buckets.
The broker will instantiate downscoped credentials instances that can be used to generate short lived downscoped access tokens which will be passed to the token consumer.
1const {OAuth2Client} = require('google-auth-library'); 2const {Storage} = require('@google-cloud/storage'); 3 4// Create the OAuth credentials (the consumer). 5const oauth2Client = new OAuth2Client(); 6// We are defining a refresh handler instead of a one-time access 7// token/expiry pair. 8// This will allow the consumer to obtain new downscoped tokens on 9// demand every time a token is expired, without any additional code 10// changes. 11oauth2Client.refreshHandler = async () => { 12 // The common pattern of usage is to have a token broker pass the 13 // downscoped short-lived access tokens to a token consumer via some 14 // secure authenticated channel. 15 const refreshedAccessToken = await cabClient.getAccessToken(); 16 return { 17 access_token: refreshedAccessToken.token, 18 expiry_date: refreshedAccessToken.expirationTime, 19 } 20}; 21 22// Use the consumer client to define storageOptions and create a GCS object. 23const storageOptions = { 24 projectId: 'my_project_id', 25 authClient: oauth2Client, 26}; 27 28const storage = new Storage(storageOptions); 29 30const downloadFile = await storage 31 .bucket('bucket_name') 32 .file('customer-a-data.txt') 33 .download(); 34console.log(downloadFile.toString('utf8')); 35 36main().catch(console.error);
Samples are in the samples/
directory. Each sample's README.md
has instructions for running its sample.
Sample | Source Code | Try it |
---|---|---|
Adc | source code | |
Authenticate API Key | source code | |
Authenticate Explicit | source code | |
Authenticate Implicit With Adc | source code | |
Compute | source code | |
Credentials | source code | |
Downscopedclient | source code | |
Headers | source code | |
Id Token From Impersonated Credentials | source code | |
Id Token From Metadata Server | source code | |
Id Token From Service Account | source code | |
ID Tokens for Identity-Aware Proxy (IAP) | source code | |
ID Tokens for Serverless | source code | |
Jwt | source code | |
Keepalive | source code | |
Keyfile | source code | |
Oauth2-code Verifier | source code | |
Oauth2 | source code | |
Sign Blob | source code | |
Sign Blob Impersonated | source code | |
Verify Google Id Token | source code | |
Verifying ID Tokens from Identity-Aware Proxy (IAP) | source code | |
Verify Id Token | source code |
The Google Auth Library Node.js Client API Reference documentation also contains samples.
Our client libraries follow the Node.js release schedule. Libraries are compatible with all current active and maintenance versions of Node.js. If you are using an end-of-life version of Node.js, we recommend that you update as soon as possible to an actively supported LTS version.
Google's client libraries support legacy versions of Node.js runtimes on a best-efforts basis with the following warnings:
Client libraries targeting some end-of-life versions of Node.js are available, and
can be installed through npm dist-tags.
The dist-tags follow the naming convention legacy-(version)
.
For example, npm install google-auth-library@legacy-8
installs client libraries
for versions compatible with Node.js 8.
This library follows Semantic Versioning.
This library is considered to be stable. The code surface will not change in backwards-incompatible ways unless absolutely necessary (e.g. because of critical security issues) or with an extensive deprecation period. Issues and requests against stable libraries are addressed with the highest priority.
More Information: Google Cloud Platform Launch Stages
Contributions welcome! See the Contributing Guide.
Please note that this README.md
, the samples/README.md
,
and a variety of configuration files in this repository (including .nycrc
and tsconfig.json
)
are generated from a central template. To edit one of these files, make an edit
to its templates in
directory.
Apache Version 2.0
See LICENSE
No vulnerabilities found.
Reason
security policy file detected
Details
Reason
no dangerous workflow patterns detected
Reason
all changesets reviewed
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
10 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 8
Reason
SAST tool is not run on all commits -- score normalized to 7
Details
Reason
dependency not pinned by hash detected -- score normalized to 1
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More