### Complete OAuth2 Workflow Example Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md This example demonstrates a full OAuth2 authentication flow, including acquiring credentials, making an API request, and handling token information. It requires an 'oauth2.keys.json' file for configuration. ```javascript 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 `fetch` and // `request` methods accept a [`GaxiosOptions`](https://github.com/googleapis/gaxios) // object. const url = 'https://people.googleapis.com/v1/people/me?personFields=names'; const res = await oAuth2Client.fetch(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({ clientId: keys.web.client_id, clientSecret: keys.web.client_secret, redirectUri: 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= 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); ``` -------------------------------- ### Install Dependencies Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/CONTRIBUTING.md Install project dependencies using npm. This is a prerequisite for running tests and development. ```bash npm install ``` -------------------------------- ### Install Google Auth Library Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md Install the google-auth-library using npm. This is the first step to using the library in your Node.js project. ```bash npm install google-auth-library ``` -------------------------------- ### Example: Using UserRefreshClient Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-others.md Shows how to create a UserRefreshClient with provided OAuth credentials and then retrieve an access token. ```typescript const client = new UserRefreshClient({ clientId: 'client-id.apps.googleusercontent.com', clientSecret: 'client-secret', refreshToken: 'stored-refresh-token' }); const {token} = await client.getAccessToken(); ``` -------------------------------- ### ExternalAccountAuthorizedUserClient Usage Example Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-others.md Example of how to instantiate and use the ExternalAccountAuthorizedUserClient to obtain an access token. Ensure you have the necessary credentials and audience configured. ```typescript import {ExternalAccountAuthorizedUserClient} from 'google-auth-library'; const client = new ExternalAccountAuthorizedUserClient({ type: 'external_account_authorized_user', client_id: 'client-id', client_secret: 'client-secret', refresh_token: 'refresh-token', audience: 'workforce-audience', subject_token_type: 'token-type' }); const {token} = await client.getAccessToken(); ``` -------------------------------- ### Example: Using ExternalAccountClient.fromJSON Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-others.md Demonstrates how to load an external account configuration from a JSON file and obtain an access token using the created client. ```typescript import {ExternalAccountClient} from 'google-auth-library'; import * as fs from 'fs'; const config = JSON.parse( fs.readFileSync('/path/to/external-account-config.json', 'utf8') ); const client = ExternalAccountClient.fromJSON(config); const {token} = await client.getAccessToken(); ``` -------------------------------- ### IAMAuth Usage Example Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-others.md Demonstrates how to use the IAMAuth class to get request metadata signed with IAM. This requires an existing GoogleAuth client and a target service account. ```typescript import {IAMAuth} from 'google-auth-library'; import {GoogleAuth} from 'google-auth-library'; const auth = new GoogleAuth(); const baseClient = await auth.getClient(); const iamAuth = new IAMAuth( 'target-sa@project.iam.gserviceaccount.com', baseClient ); const headers = await iamAuth.getRequestMetadata(); ``` -------------------------------- ### Fetch ID Token Example Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-compute.md Fetches a signed ID token for a specified audience. Ensure the Compute client is initialized. ```typescript const compute = new Compute(); const idToken = await compute.fetchIdToken('https://cloud-run-service.run.app'); ``` -------------------------------- ### Get Access Token Example Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-compute.md Retrieves the current access token, refreshing it from the metadata server if it has expired. The response includes the token and its expiry date. ```typescript const compute = new Compute(); const {token} = await compute.getAccessToken(); ``` -------------------------------- ### Authenticate with Google Compute Engine Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/INDEX.md This example shows how to authenticate using credentials from the Google Compute Engine metadata server. It requires the appropriate scopes for accessing Google Cloud Platform resources. ```typescript import {Compute} from 'google-auth-library'; const compute = new Compute({ scopes: 'https://www.googleapis.com/auth/cloud-platform' }); const response = await compute.fetch('https://www.googleapis.com/...'); ``` -------------------------------- ### Sign Blob Example Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-compute.md Signs arbitrary bytes using the service account private key via the metadata server. The data to be signed must be provided as a Buffer. ```typescript const compute = new Compute(); const data = Buffer.from('data to sign'); const {signature, keyId} = await compute.signBlob(data); ``` -------------------------------- ### Fetch Authenticated HTTP Request Example Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-compute.md Makes an authenticated HTTP request to Google APIs. Specify the URL and optional GaxiosOptions for the request. ```typescript const compute = new Compute({ scopes: 'https://www.googleapis.com/auth/cloud-platform' }); const response = await compute.fetch( 'https://www.googleapis.com/compute/v1/projects/my-project/zones/us-central1-a/instances' ); console.log(response.data.items); ``` -------------------------------- ### Generate SAML Config from URL Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md Generates a SAML configuration file for URL-sourced credentials. A local server must host a GET endpoint that returns the SAML assertion. Additional headers can be specified. ```bash 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 ``` -------------------------------- ### Impersonate a Service Account Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/INDEX.md This example demonstrates how to impersonate a service account to access resources with its permissions. It requires a source client, the target service account principal, and the desired scopes. ```typescript import {GoogleAuth, Impersonated} from 'google-auth-library'; const auth = new GoogleAuth(); const sourceClient = await auth.getClient(); const impersonated = new Impersonated({ sourceClient, targetPrincipal: 'target-sa@project.iam.gserviceaccount.com', targetScopes: ['https://www.googleapis.com/auth/cloud-platform'] }); const {token} = await impersonated.getAccessToken(); ``` -------------------------------- ### Generate OIDC Config from URL Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md Generates an OIDC configuration file for URL-sourced credentials. A local server must host a GET endpoint that returns the OIDC token. Additional headers can be specified. ```bash 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 ``` -------------------------------- ### Generate URL-Sourced OIDC Credentials Config Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md Use this command to generate an OIDC configuration file when the OIDC token is served from a URL. This requires a local server to host a GET endpoint for the token. Additional headers can be specified for the request. ```bash gcloud iam workload-identity-pools create-cred-config \ projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$OIDC_PROVIDER_ID \ --service-account $SERVICE_ACCOUNT_EMAIL \ --credential-source-url $URL_TO_GET_OIDC_TOKEN \ --credential-source-headers $HEADER_KEY=$HEADER_VALUE \ --output-file /path/to/generated/config.json ``` -------------------------------- ### Handle JWT Private Key Issues Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/errors.md Manage errors related to JWT private key configuration, including missing files, incorrect formats, or permission issues. This example demonstrates specific error code checks for common problems. ```typescript try { const jwt = new JWT({ email: 'service-account@project.iam.gserviceaccount.com', keyFile: '/path/to/key.json' }); const token = await jwt.getAccessToken(); } catch (err) { if (err.code === 'ENOENT') { console.log('Key file not found'); } else if (err.code === 'EACCES') { console.log('No permission to read key file'); } else if (err.message.includes('PEM')) { console.log('Invalid key format'); } } ``` -------------------------------- ### Configure JWT Client with Service Account Keys from File Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md Set up a JWT client for authenticating requests using a service account's JSON key file. Ensure the `jwt.keys.json` file contains the necessary credentials. ```javascript const {JWT} = require('google-auth-library'); const keys = require('./jwt.keys.json'); const client = new JWT({ email: keys.client_email, key: keys.private_key, scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`; const res = await client.fetch(url); console.log(res.data); ``` -------------------------------- ### Configure JWT Client with Constructor Options Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/configuration.md Initialize a JWT client with service account email, private key, key file path, key ID, scopes, subject, and additional claims. ```typescript const jwt = new JWT({ email: 'service-account@project.iam.gserviceaccount.com', key: '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n', keyFile: '/path/to/private-key.pem', keyId: 'KEY_ID_FROM_CONSOLE', scopes: 'https://www.googleapis.com/auth/cloud-platform', subject: 'user@example.com', additionalClaims: {target_audience: 'https://service-url.run.app'} }); ``` -------------------------------- ### getRequestMetadata Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-jwt.md Gets the authorization headers for a request. ```APIDOC ## getRequestMetadata(url?: string | null) ### Description Gets the authorization headers for a request. ### Signature ```typescript getRequestMetadata(url?: string | null): Promise<{headers: {Authorization: string}}> ``` ### Parameters #### Path Parameters - **url** (`string | null`) - Optional - Request URL for scope validation. ### Returns - `Promise` Headers object. ### Example ```javascript const metadata = await jwt.getRequestMetadata(); console.log(metadata.headers.Authorization); ``` ``` -------------------------------- ### getAccessToken() Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-others.md Gets a Google access token using AWS credentials. ```APIDOC ## getAccessToken() Gets a Google access token using AWS credentials. ```typescript getAccessToken(): Promise ``` ``` -------------------------------- ### AuthClient Constructor Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-authclient.md Initializes the AuthClient with optional configuration settings. ```APIDOC ## Constructor ```typescript constructor(options?: AuthClientOptions) ``` ### AuthClientOptions | Option | Type | Required | Default | Description | |---|---|---|---|---| | apiKey | `string` | No | undefined | API key for public access | | credentials | `Credentials` | No | undefined | Initial credential tokens | | projectId | `string` | No | undefined | Google Cloud project ID | | quotaProjectId | `string` | No | undefined | Project for quota/billing | | universe | `string` | No | 'googleapis.com' | Cloud universe domain | | eagerRefreshThresholdMillis | `number` | No | 300000 | Token refresh threshold | | forceRefreshOnFailure | `boolean` | No | false | Auto-refresh on 401 | ``` -------------------------------- ### fetchIdToken(targetAudience: string) Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-others.md Gets an ID token using AWS identity. ```APIDOC ## fetchIdToken(targetAudience: string) Gets an ID token using AWS identity. ```typescript fetchIdToken(targetAudience: string): Promise ``` ``` -------------------------------- ### Run Sample Integration Tests Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/CONTRIBUTING.md Execute sample integration tests using the npm run samples-test command. This helps verify the integration of samples with the library. ```bash # Run sample integration tests. npm run samples-test ``` -------------------------------- ### getAccessToken Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-compute.md Gets the current access token, refreshing from the metadata server if it has expired. ```APIDOC ## Method getAccessToken ### Description Gets the current access token, refreshing from the metadata server if expired. ### Signature ```typescript getAccessToken(): Promise ``` ### Returns - `Promise` - An object with the `token` and `expiryDate`. ### Example ```typescript const compute = new Compute(); const {token} = await compute.getAccessToken(); ``` ``` -------------------------------- ### Configure GoogleAuth with Constructor Options Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/configuration.md Instantiate GoogleAuth with various configuration options like API key, key file path, scopes, and project ID. ```typescript const auth = new GoogleAuth({ apiKey: 'YOUR_API_KEY', keyFilename: '/path/to/credentials.json', scopes: 'https://www.googleapis.com/auth/cloud-platform', projectId: 'my-project', clientOptions: { quotaProjectId: 'quota-project' } }); ``` -------------------------------- ### getAccessToken Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-jwt.md Gets the current access token, generating a new self-signed JWT if needed. ```APIDOC ## getAccessToken() ### Description Gets the current access token, generating a new self-signed JWT if needed. ### Signature ```typescript getAccessToken(): Promise ``` ### Returns - `Promise` Object with `token` and `expiryDate`. ### Throws - `Error` if unable to sign JWT or fetch token. ### Example ```javascript const jwt = new JWT({ email: 'service-account@project.iam.gserviceaccount.com', key: privateKeyPem, scopes: 'https://www.googleapis.com/auth/cloud-platform' }); const {token} = await jwt.getAccessToken(); ``` ``` -------------------------------- ### getAccessToken() Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-authclient.md Gets the current access token, refreshing it if necessary. This method is implemented by all subclasses. ```APIDOC ## getAccessToken() Gets the current access token, refreshing if necessary. ```typescript abstract getAccessToken(): Promise ``` **Returns:** `Promise` Object with `token` and `expiryDate` **Throws:** - `Error` if unable to obtain token **Implemented by all subclasses** ``` -------------------------------- ### Run Unit Tests Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/CONTRIBUTING.md Execute the project's unit tests using the npm test command. Ensure all unit tests pass before submitting changes. ```bash # Run unit tests. npm test ``` -------------------------------- ### Generate X.509 Credential Config (Default Location) Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md Use this command to create X.509 credential configuration files when you want the certificate configuration to be automatically discovered by client libraries. Substitute placeholder variables with your specific project details. ```bash gcloud iam workload-identity-pools create-cred-config \ projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$PROVIDER_ID \ --service-account $SERVICE_ACCOUNT_EMAIL \ --credential-cert-path "$PATH_TO_CERTIFICATE" \ --credential-cert-private-key-path "$PATH_TO_PRIVATE_KEY" \ --credential-cert-trust-chain-path "$PATH_TO_TRUST_CHAIN" \ --output-file /path/to/config.json ``` -------------------------------- ### Initialize ExternalAccountClient from JSON Configuration Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md Explicitly initialize an ExternalAccountClient using a JSON configuration file. Set the desired scopes for the client. ```javascript const {ExternalAccountClient} = require('google-auth-library'); const jsonConfig = require('/path/to/config.json'); 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.fetch(url); console.log(res.data); ``` -------------------------------- ### Get Request Headers Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-oauth2client.md Generates the necessary authorization headers for an HTTP request. An optional URL can be provided for scope validation. ```typescript const headers = await client.getRequestHeaders(); const res = await fetch('https://www.googleapis.com/drive/v3/files', {headers}); ``` -------------------------------- ### Generate SAML Config from File Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md Generates a SAML configuration file for file-sourced credentials. The credential source file should contain the SAML assertion. ```bash 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 ``` -------------------------------- ### AwsSecurityCredentialsSupplier Interface Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/types.md An interface for custom suppliers of AWS credentials. It requires methods to get the AWS region and the security credentials themselves. ```typescript interface AwsSecurityCredentialsSupplier { getAwsRegion(context: ExternalAccountSupplierContext): Promise; getAwsSecurityCredentials(context: ExternalAccountSupplierContext): Promise; } ``` -------------------------------- ### Create Executable Credential Configuration Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md Use this command to generate a configuration file for executable-sourced credentials. Substitute the placeholder variables with your specific project and workload identity pool details. ```bash 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 \ --executable-command=$EXECUTABLE_COMMAND \ --output-file /path/to/generated/config.json ``` -------------------------------- ### Get Universe Domain using GoogleAuth Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-googleauth.md Retrieves the universe domain that the GoogleAuth instance will use. This defaults to 'googleapis.com' but can be configured. ```typescript const auth = new GoogleAuth(); const universe = await auth.getUniverseDomain(); ``` -------------------------------- ### Get Request Metadata Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-jwt.md Fetches the necessary authorization headers for an API request. The optional URL parameter can be used for scope validation. ```typescript const metadata = await jwt.getRequestMetadata(); console.log(metadata.headers.Authorization); ``` -------------------------------- ### Get Request Headers Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-authclient.md Retrieves HTTP headers required for authenticated requests. The optional URL parameter can be used for validation purposes. ```typescript const headers = await client.getRequestHeaders(); const response = await fetch('https://api.example.com', {headers}); ``` -------------------------------- ### Compute Constructor Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-compute.md Initializes a new instance of the Compute client. It can be configured with options such as service account email, scopes, and API key. ```APIDOC ## Constructor Compute ### Description Initializes a new instance of the Compute client. ### Signature ```typescript constructor(options?: ComputeOptions) ``` ### Parameters #### Options - **options** (`ComputeOptions`) - Optional - Configuration options for the Compute client. - **serviceAccountEmail** (`string`) - Optional - Defaults to 'default'. The service account email or name. - **scopes** (`string | string[]`) - Optional - Defaults to `[]`. OAuth scopes for the service account. - **apiKey** (`string`) - Optional - Google API key for public access. ``` -------------------------------- ### Create JWT Client from Service Account Key File Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-jwt.md Initialize a JWT client by parsing a service account key JSON file. This is a common way to authenticate when running applications outside of Google Cloud environments. ```typescript import {JWT} from 'google-auth-library'; import * as fs from 'fs'; const keyfile = JSON.parse( fs.readFileSync('/path/to/service-account-key.json', 'utf8') ); const jwt = new JWT({ email: keyfile.client_email, key: keyfile.private_key, scopes: ['https://www.googleapis.com/auth/cloud-platform'] }); ``` -------------------------------- ### Run System Tests Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/CONTRIBUTING.md Execute all system tests using the npm run system-test command. This provides comprehensive testing of the library's functionality. ```bash # Run all system tests. npm run system-test ``` -------------------------------- ### Get Token Information Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md Retrieve details about an access token, such as its expiration date, scopes, and audience. This method throws an error if the token is invalid. ```javascript const tokenInfo = await oAuth2Client.getTokenInfo('my-access-token'); console.log(tokenInfo.scopes); ``` -------------------------------- ### Configure OAuth2Client with Constructor Options Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/configuration.md Instantiate OAuth2Client with options such as client ID, client secret, redirect URI, and refresh thresholds. ```typescript const client = new OAuth2Client({ clientId: 'YOUR_CLIENT_ID.apps.googleusercontent.com', clientSecret: 'YOUR_CLIENT_SECRET', redirectUri: 'http://localhost:3000/oauth2callback', eagerRefreshThresholdMillis: 5 * 60 * 1000, forceRefreshOnFailure: false }); ``` -------------------------------- ### Get Token Info Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-oauth2client.md Fetches metadata for a given access token, including its scopes and expiration. The provided access token must be valid. ```typescript const tokenInfo = await client.getTokenInfo('ya29.a0AfH6SMBx...'); console.log('Scopes:', tokenInfo.scopes); console.log('Expires:', new Date(tokenInfo.expiry_date)); ``` -------------------------------- ### Get Access Token Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-oauth2client.md Retrieves the current access token, refreshing it if it's expired. Ensure the client is configured with valid credentials before calling. ```typescript const {token} = await client.getAccessToken(); console.log('Bearer', token); ``` -------------------------------- ### Get Credentials JSON using GoogleAuth Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-googleauth.md Obtains the raw JSON credential configuration object. This is useful for inspecting the loaded credentials, such as the client email. ```typescript const auth = new GoogleAuth({keyFilename: '/path/to/credentials.json'}); const creds = await auth.getCredentials(); console.log(creds.client_email); ``` -------------------------------- ### Basic Compute Authentication Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-compute.md Demonstrates basic authentication using the Compute class with the default service account. Imports the Compute class from 'google-auth-library'. ```typescript import {Compute} from 'google-auth-library'; // Use default service account const auth = new Compute(); // Make authenticated requests const response = await auth.fetch('https://www.googleapis.com/storage/v1/b'); console.log('Buckets:', response.data.items); ``` -------------------------------- ### Initialize GoogleAuth with API Key via Client Options Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md Configure GoogleAuth to pass an API key to any generated OAuth2Client instances using the `clientOptions` parameter. ```javascript const auth = new GoogleAuth({ clientOptions: { apiKey: 'my-api-key' } }) ``` -------------------------------- ### Get Google Access Token using AWS Credentials Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-others.md Retrieves a Google access token by leveraging AWS credentials. This method is part of the AWS client functionality. ```typescript getAccessToken(): Promise ``` -------------------------------- ### Generate X.509 Credential Config (Custom Location) Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md Use this command to create X.509 credential configuration files when you need to specify a custom location for the certificate configuration file. Substitute placeholder variables with your specific project details. ```bash gcloud iam workload-identity-pools create-cred-config \ projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/$POOL_ID/providers/$PROVIDER_ID \ --service-account $SERVICE_ACCOUNT_EMAIL \ --credential-cert-path "$PATH_TO_CERTIFICATE" \ --credential-cert-private-key-path "$PATH_TO_PRIVATE_KEY" \ --credential-cert-trust-chain-path "$PATH_TO_TRUST_CHAIN" \ --credential-cert-configuration-output-file "/custom/path/cert_config.json" \ --output-file /path/to/config.json ``` -------------------------------- ### Get Access Token with JWT Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-jwt.md Retrieves the current access token, generating a new self-signed JWT if necessary. Ensure the JWT client is configured with the required scopes. ```typescript const jwt = new JWT({ email: 'service-account@project.iam.gserviceaccount.com', key: privateKeyPem, scopes: 'https://www.googleapis.com/auth/cloud-platform' }); const {token} = await jwt.getAccessToken(); ``` -------------------------------- ### Generate OIDC Config from File Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md Generates an OIDC configuration file for file-sourced credentials. Ensure the credential source file contains the OIDC ID token. ```bash gcloud iam workforce-pools create-cred-config \ locations/global/workforcePools/$WORKFORCE_POOL_ID/providers/$PROVIDER_ID \ --subject-token-type=urn:ietf:params:oauth:token-type:id_token \ --credential-source-file=$PATH_TO_OIDC_ID_TOKEN \ --workforce-pool-user-project=$WORKFORCE_POOL_USER_PROJECT \ --output-file=/path/to/generated/config.json ``` -------------------------------- ### PluggableAuthClient Constructor Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-others.md Handles executable-sourced external credentials through local executables. Requires configuration for the credential source, audience, subject token type, and token URL. ```APIDOC ## PluggableAuthClient Constructor ### Description Handles executable-sourced external credentials through local executables. ### Constructor ```typescript constructor(options: PluggableAuthClientOptions) ``` ### Parameters #### Request Body - **credential_source** (object) - Required - Executable configuration. - **audience** (string) - Required - Workload identity pool audience. - **subject_token_type** (string) - Required - Token type from executable. - **token_url** (string) - Required - STS endpoint. ### credential_source for Executables ```typescript credential_source: { executable: { command: string; // Full command path with args timeout_millis?: number; // Timeout in milliseconds (5000-120000) interactive_timeout_millis?: number; // Interactive mode timeout }, format?: { type: 'text' | 'json', subject_token_field_name?: string } } ``` ### Environment Variables The executable receives: - `GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE` - `GOOGLE_EXTERNAL_ACCOUNT_SUBJECT_TOKEN_TYPE` - `GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL` - `GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE` ``` -------------------------------- ### Get Project ID using GoogleAuth Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-googleauth.md Retrieves the default project ID for the application. This method automatically detects the project ID from various sources, prioritizing constructor options. ```typescript const auth = new GoogleAuth(); const projectId = await auth.getProjectId(); console.log('Project ID:', projectId); ``` -------------------------------- ### OAuth2Client Constructor Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-oauth2client.md Initializes a new instance of the OAuth2Client class with optional configuration options. ```APIDOC ## Constructor OAuth2Client ### Description Initializes a new instance of the OAuth2Client class with optional configuration options. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### options (`OAuth2ClientOptions`) - **options** (OAuth2ClientOptions) - Optional - Configuration options for OAuth2Client ### OAuth2ClientOptions - **clientId** (string) - Optional - OAuth 2.0 client ID - **clientSecret** (string) - Optional - OAuth 2.0 client secret - **redirectUri** (string) - Optional - OAuth 2.0 redirect URI - **apiKey** (string) - Optional - Google API key for public access - **credentials** (Credentials) - Optional - Initial credential object with tokens - **eagerRefreshThresholdMillis** (number) - Optional - Milliseconds before expiry to consider token expired (Default: `5 * 60 * 1000`) - **forceRefreshOnFailure** (boolean) - Optional - Automatically refresh on 401 responses (Default: `false`) ``` -------------------------------- ### TypeScript Usage with Google Auth Library Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-authclient.md Demonstrates how to use the Google Auth Library in TypeScript for type-safe client instantiation, request handling, and token retrieval. Ensure necessary imports are included. ```typescript import {AuthClient, JWT, OAuth2Client} from 'google-auth-library'; // Type-safe client const client: AuthClient = new JWT({ email: 'sa@project.iam.gserviceaccount.com', key: key }); // Typed response interface FilesListResponse { files: Array<{id: string; name: string}> } const response = await client.request({ url: 'https://www.googleapis.com/drive/v3/files' }); // Type-safe token const {token}: GetAccessTokenResponse = await client.getAccessToken(); ``` -------------------------------- ### Handle Compute Engine Wrong Service Account Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/errors.md Address errors when the specified service account is not attached to the GCE instance. This example checks for a 404 status code to identify the issue. ```typescript const compute = new Compute({ serviceAccountEmail: 'sa-name@project.iam.gserviceaccount.com' }); try { const token = await compute.getAccessToken(); } catch (err) { if (err.status === 404) { console.log('Service account not attached to this GCE instance'); } } ``` -------------------------------- ### Initialize with Application Default Credentials Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/README.md Initialize GoogleAuth with specified scopes to obtain a client for Application Default Credentials. Use this to make authenticated requests. ```typescript import {GoogleAuth} from 'google-auth-library'; const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/cloud-platform' }); const client = await auth.getClient(); const response = await client.fetch('https://www.googleapis.com/...'); ``` -------------------------------- ### Get AuthClient using GoogleAuth Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-googleauth.md Obtains an authenticated AuthClient instance. If a client is provided during initialization, it's returned directly; otherwise, the library detects the appropriate client based on the environment. ```typescript const auth = new GoogleAuth(); const client = await auth.getClient(); const res = await client.fetch('https://www.googleapis.com/storage/v1/b'); ``` -------------------------------- ### JWT Constructor Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-jwt.md Initializes a new instance of the JWT class with optional configuration options. ```APIDOC ## JWT Constructor ### Description Initializes a new instance of the JWT class with optional configuration options. ### Signature ```typescript constructor(options?: JWTOptions) ``` ### Parameters #### Options - **options** (`JWTOptions`) - Optional - Configuration options for JWT. ##### JWTOptions extends OAuth2ClientOptions - **email** (`string`) - Optional - Service account email address. - **key** (`string`) - Optional - Private key PEM string (preferred over keyFile). - **keyFile** (`string`) - Optional - Path to private key PEM file. - **keyId** (`string`) - Optional - Private key ID from service account JSON. - **scopes** (`string | string[]`) - Optional - OAuth scopes to request. - **subject** (`string`) - Optional - User email for domain-wide delegation. - **additionalClaims** (`{[key: string]: any}`) - Optional - Additional JWT claims (e.g., target_audience). - **apiKey** (`string`) - Optional - Google API key for public access. - **credentials** (`Credentials`) - Optional - Initial credentials. ``` -------------------------------- ### Domain-Wide Delegation with JWT Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-jwt.md Configure a JWT client to impersonate a user in Google Workspace using domain-wide delegation. This requires specific setup in the Google Admin console and the service account. ```typescript const jwt = new JWT({ email: 'service-account@my-domain.iam.gserviceaccount.com', key: privateKeyPem, scopes: 'https://www.googleapis.com/auth/admin.directory.user', subject: 'admin@my-domain.com' }); // Now makes requests as admin@my-domain.com const response = await jwt.fetch( 'https://www.googleapis.com/admin/directory/v1/users' ); ``` -------------------------------- ### Configure API Key Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-authclient.md Initialize AuthClient with an `apiKey` to make authenticated calls to public APIs that do not require OAuth 2.0 credentials. This is useful for accessing services like the YouTube Data API. ```typescript const client = new OAuth2Client({ apiKey: 'YOUR_API_KEY' }); // Make public API calls (no authentication needed) const response = await client.fetch('https://www.googleapis.com/youtube/v3/search?q=...'); ``` -------------------------------- ### Custom AWS Security Credentials Supplier Implementation Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md Implement a custom supplier to retrieve AWS security credentials when native methods are not supported. This example shows how to use `@aws-sdk/credential-providers` to fetch credentials. ```typescript 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 = region; } async getAwsRegion(context: ExternalAccountSupplierContext): Promise { // Return the AWS region i.e. "us-east-2". return this.region } async getAwsSecurityCredentials( context: ExternalAccountSupplierContext ): Promise { // 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. service_account_impersonation_url: 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/$EMAIL:generateAccessToken', // Set the service account impersonation url. } // 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 }); ``` -------------------------------- ### PKCE Flow Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-oauth2client.md Demonstrates the Proof Key for Code Exchange (PKCE) flow, enhancing security for public clients by using a dynamically generated secret to verify the authorization code. ```APIDOC ## PKCE (Proof Key for Code Exchange) ### Description For enhanced security with public clients, the PKCE flow is recommended. It involves generating a code verifier and challenge to secure the authorization code exchange. ### Generate code verifier and challenge ```typescript const verifier = crypto.randomBytes(32).toString('hex'); const challenge = crypto .createHash('sha256') .update(verifier) .digest('base64') .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=/g, ''); const url = client.generateAuthUrl({ access_type: 'offline', scope: 'https://www.googleapis.com/auth/drive', code_challenge: challenge, code_challenge_method: 'S256' }); ``` ### Exchange authorization code for tokens ```typescript // After user approves: const {tokens} = await client.getToken({ code: authCode, codeVerifier: verifier }); ``` ``` -------------------------------- ### Configure Compute Engine Client Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/configuration.md Instantiate a Compute Engine client with a specific service account and OAuth scopes. Use this when running on Compute Engine and needing to authenticate as a specific service account. ```typescript const compute = new Compute({ serviceAccountEmail: 'my-service-account@project.iam.gserviceaccount.com', scopes: 'https://www.googleapis.com/auth/cloud-platform' }); ``` -------------------------------- ### getClient() Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-googleauth.md Obtains an authenticated AuthClient instance. If a client was provided during initialization, it is returned directly. Otherwise, an appropriate client is automatically detected based on the environment. ```APIDOC ## getClient() ### Description Obtains an AuthClient. If one is provided in constructor options, returns it directly. Otherwise, automatically detects the appropriate client type based on the environment. ### Signature ```typescript getClient(): Promise ``` ### Returns - `Promise` An AuthClient instance (JWT, Compute, OAuth2Client, etc.) ### Throws - `Error` with message `NO_CREDENTIALS_FOUND` if no credentials can be detected ### Example ```typescript const auth = new GoogleAuth(); const client = await auth.getClient(); const res = await client.fetch('https://www.googleapis.com/storage/v1/b'); ``` ``` -------------------------------- ### Get GoogleAuth Client for Application Default Credentials Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/INDEX.md Use this snippet to obtain a client for making authenticated requests using Application Default Credentials (ADC). The library automatically detects credentials. ```typescript import {GoogleAuth} from 'google-auth-library'; const auth = new GoogleAuth(); const client = await auth.getClient(); const response = await client.fetch('https://www.googleapis.com/...'); ``` -------------------------------- ### Set Cloud Universe Domain Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/configuration.md Configure the Cloud universe domain using the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable. Defaults to 'googleapis.com'. ```bash export GOOGLE_CLOUD_UNIVERSE_DOMAIN=googleapis.com ``` -------------------------------- ### Fetch ID Token for IAP Resource Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md Fetch an ID token to access a protected Identity-Aware Proxy (IAP) resource. The target audience must be the Client ID used during IAP setup. ```js // Make a request to a protected Cloud Identity-Aware Proxy (IAP) resource const {GoogleAuth} = require('google-auth-library'); 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.fetch(url); console.log(res.data); ``` -------------------------------- ### Configure Impersonated Client Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/configuration.md Set up an Impersonated client to act as another service account. Requires a base authenticated client, the target principal's service account email, and desired scopes. ```typescript const impersonated = new Impersonated({ sourceClient: authenticatedClient, targetPrincipal: 'target-sa@project.iam.gserviceaccount.com', targetScopes: ['https://www.googleapis.com/auth/cloud-platform'], delegates: ['delegate1@project.iam.gserviceaccount.com'], lifetime: 3600, endpoint: 'https://iamcredentials.googleapis.com/v1' }); ``` -------------------------------- ### Handle Token Acquisition and Errors Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-oauth2client.md Attempt to get tokens using an authorization code and set them on the client. Includes specific error handling for common HTTP status codes like 400 and 401. ```typescript try { const {tokens} = await client.getToken(code); client.setCredentials(tokens); } catch (err) { if (err.status === 400) { console.log('Invalid or expired authorization code'); } else if (err.status === 401) { console.log('Client authentication failed'); } } ``` -------------------------------- ### Get Impersonated Access Token Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-others.md Use the Impersonated class to obtain short-lived credentials by impersonating a service account. This is useful when you need to perform actions on behalf of another service account with specific scopes. ```typescript const auth = new GoogleAuth(); const sourceClient = await auth.getClient(); const impersonated = new Impersonated({ sourceClient, targetPrincipal: 'target-sa@project.iam.gserviceaccount.com', targetScopes: ['https://www.googleapis.com/auth/cloud-platform'] }); const {token} = await impersonated.getAccessToken(); ``` -------------------------------- ### Configure PluggableAuthClient Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/configuration.md Instantiate PluggableAuthClient with specific configuration for audience, token type, token URL, and credential source details. ```typescript const pluggableAuthClient = new PluggableAuthClient({ audience: '//iam.googleapis.com/projects/.../providers/...', subject_token_type: 'urn:ietf:params:oauth:token-type:jwt', token_url: 'https://sts.googleapis.com/v1/token', credential_source: { executable: { command: '/path/to/script.sh arg1 arg2', timeout_millis: 30000, interactive_timeout_millis: 30000 }, format: { type: 'json', subject_token_field_name: 'token' } } }); ``` -------------------------------- ### Initialize OAuth2Client with API Key Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md Instantiate an OAuth2Client directly with an API key. This key can be used for APIs that support key-based authentication. ```javascript const client = new OAuth2Client({ apiKey: 'my-api-key' }); ``` -------------------------------- ### Error Handling for JWT Authentication Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-jwt.md Implement robust error handling for JWT authentication operations. This example shows how to catch and differentiate common errors like file not found, authentication failures, and permission issues. ```typescript try { const jwt = new JWT({ email: 'service-account@project.iam.gserviceaccount.com', key: privateKeyPem, scopes: 'https://www.googleapis.com/auth/cloud-platform' }); const response = await jwt.fetch('https://storage.googleapis.com/storage/v1/b'); } catch (err) { if (err.message.includes('ENOENT')) { console.log('Key file not found'); } else if (err.status === 401) { console.log('Authentication failed'); } else if (err.status === 403) { console.log('Insufficient permissions'); } } ``` -------------------------------- ### Instantiate OAuth2Client Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-oauth2client.md Instantiate the OAuth2Client with configuration options like client ID, client secret, and redirect URI. ```typescript const client = new OAuth2Client({ clientId: 'your-client-id.apps.googleusercontent.com', clientSecret: 'your-client-secret', redirectUri: 'http://localhost:3000/oauth2callback' }); ``` -------------------------------- ### Get Downscoped Access Token with Credential Access Boundaries Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/api-reference-others.md Create downscoped access tokens with restricted permissions using the DownscopedClient. This is ideal for scenarios where you need to grant temporary, limited access to specific resources. ```typescript const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/cloud-platform' }); const sourceClient = await auth.getClient(); const cab = { accessBoundary: { accessBoundaryRules: [{ availableResource: '//storage.googleapis.com/bucket-name', availablePermissions: ['inRole:roles/storage.objectViewer'], availabilityCondition: { expression: `resource.name.startsWith('projects/_/buckets/bucket-name/objects/prefix')` } }] } }; const downscoped = new DownscopedClient({ authClient: sourceClient, credentialAccessBoundary: cab }); const {token} = await downscoped.getAccessToken(); ``` -------------------------------- ### Initialize GoogleAuth with Application Default Credentials Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md Initialize GoogleAuth with scopes to automatically use credentials from the GOOGLE_APPLICATION_CREDENTIALS environment variable. This allows for automatic project ID discovery. ```javascript const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/cloud-platform' }); 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.fetch(url); console.log(res.data); ``` -------------------------------- ### Handle Subject Token Retrieval Failures Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/errors.md Manage errors when obtaining a subject token from an external provider. This example checks for file not found errors, external provider HTTP status codes, and executable-sourced credential failures. ```typescript try { const client = new IdentityPoolClient(config); const token = await client.getAccessToken(); } catch (err) { if (err.code === 'ENOENT') { console.log('Subject token file not found'); } else if (err.status >= 500) { console.log('External provider error - will retry'); } else if (err.message.includes('Executable')) { console.log('Executable-sourced credential failed'); } } ``` -------------------------------- ### Get Project ID and Fetch Data with ADC Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/README.md Automatically chooses the correct client type (JWT, OAuth2, Compute) based on the environment. Use this when you need to authenticate to Google Cloud APIs without manually specifying the credential type. Ensure the API you want to use is enabled in the Google Developers Console. ```javascript 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. */ const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/cloud-platform' }); const projectId = await auth.getProjectId(); const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; // The modern `fetch` and classic `request` APIs are available const res = await auth.fetch(url); console.log(res.data); ``` -------------------------------- ### Correct Usage of GoogleAuth Constructor with API Key or Credentials Source: https://github.com/googleapis/google-auth-library-nodejs/blob/main/_autodocs/errors.md Illustrates the correct and incorrect ways to use the GoogleAuth constructor when providing either an API key or credentials, highlighting that they are mutually exclusive. ```typescript // ✓ Correct - use API key const auth1 = new GoogleAuth({apiKey: 'KEY'}); // ✓ Correct - use credentials const auth2 = new GoogleAuth({credentials: {...}}); // ✗ Wrong - both provided const auth3 = new GoogleAuth({apiKey: 'KEY', credentials: {...}}); // Throws ```