File

src/auth/computeclient.ts

Extends

OAuth2Client

Index

Properties
Methods

Constructor

constructor(options: ComputeOptions)

Google Compute Engine service account credentials.

Retrieve access token from the metadata server. See: https://developers.google.com/compute/docs/authentication

Parameters :
Name Type Optional
options ComputeOptions No

Properties

scopes
Type : string[]
Optional _clientId
Type : string
Inherited from OAuth2Client
Defined in OAuth2Client:426
Optional _clientSecret
Type : string
Inherited from OAuth2Client
Defined in OAuth2Client:429
Optional apiKey
Type : string
Inherited from OAuth2Client
Defined in OAuth2Client:431
eagerRefreshThresholdMillis
Type : number
Inherited from OAuth2Client
Defined in OAuth2Client:435
forceRefreshOnFailure
Type : boolean
Inherited from OAuth2Client
Defined in OAuth2Client:437
Optional projectId
Type : string
Inherited from OAuth2Client
Defined in OAuth2Client:433
Optional refreshHandler
Type : GetRefreshHandlerCallback
Inherited from OAuth2Client
Defined in OAuth2Client:439

Methods

Async fetchIdToken
fetchIdToken(targetAudience: string)

Fetches an ID token.

Parameters :
Name Type Optional Description
targetAudience string No

the audience for the fetched ID token.

Returns : Promise<string>
generateAuthUrl
generateAuthUrl(opts: GenerateAuthUrlOpts)
Inherited from OAuth2Client
Defined in OAuth2Client:533

Generates URL for consent page landing.

Parameters :
Name Type Optional Default value Description
opts GenerateAuthUrlOpts No {}

Options.

Returns : string

URL to consent page.

generateCodeVerifier
generateCodeVerifier()
Inherited from OAuth2Client
Defined in OAuth2Client:554
Returns : void
Async generateCodeVerifierAsync
generateCodeVerifierAsync()
Inherited from OAuth2Client
Defined in OAuth2Client:570

Convenience method to automatically generate a code_verifier, and its resulting SHA256. If used, this must be paired with a S256 code_challenge_method.

For a full example see: https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js

getAccessToken
getAccessToken()
Inherited from OAuth2Client
Defined in OAuth2Client:742

Get a non-expired access token, after refreshing if necessary

Returns : Promise<GetAccessTokenResponse>
getFederatedSignonCerts
getFederatedSignonCerts()
Inherited from OAuth2Client
Defined in OAuth2Client:1116

Gets federated sign-on certificates to use for verifying identity tokens. Returns certs as array structure, where keys are key ids, and values are certificates in either PEM or JWK format.

Async getFederatedSignonCertsAsync
getFederatedSignonCertsAsync()
Inherited from OAuth2Client
Defined in OAuth2Client:1131
getIapPublicKeys
getIapPublicKeys()
Inherited from OAuth2Client
Defined in OAuth2Client:1204

Gets federated sign-on certificates to use for verifying identity tokens. Returns certs as array structure, where keys are key ids, and values are certificates in either PEM or JWK format.

Returns : Promise<IapPublicKeysResponse>
Async getIapPublicKeysAsync
getIapPublicKeysAsync()
Inherited from OAuth2Client
Defined in OAuth2Client:1219
Returns : Promise<IapPublicKeysResponse>
Async getRequestHeaders
getRequestHeaders(url?: string)
Inherited from OAuth2Client
Defined in OAuth2Client:795

The main authentication interface. It takes an optional url which when present is the endpoint being accessed, and returns a Promise which resolves with authorization header fields.

In OAuth2Client, the result has the form: { Authorization: 'Bearer ' }

Parameters :
Name Type Optional Description
url string Yes

The optional url being authorized

Returns : Promise<Headers>
Static getRevokeTokenUrl
getRevokeTokenUrl(token: string)
Inherited from OAuth2Client
Defined in OAuth2Client:870

Generates an URL to revoke the given token.

Parameters :
Name Type Optional Description
token string No

The existing token to be revoked.

Returns : string
getToken
getToken(code: string)
Inherited from OAuth2Client
Defined in OAuth2Client:599

Gets the access token for the given code.

Parameters :
Name Type Optional Description
code string No

The authorization code.

Returns : Promise<GetTokenResponse>
Async getTokenInfo
getTokenInfo(accessToken: string)
Inherited from OAuth2Client
Defined in OAuth2Client:1089

Obtains information about the provisioned access token. Especially useful if you want to check the scopes that were provisioned to a given token.

user info.

Parameters :
Name Type Optional Description
accessToken string No

Required. The Access Token for which you want to get user info.

Returns : Promise<TokenInfo>
refreshAccessToken
refreshAccessToken()
Inherited from OAuth2Client
Defined in OAuth2Client:714

Retrieves the access token using refresh token

Returns : Promise<RefreshAccessTokenResponse>
request
request(opts: GaxiosOptions)
Inherited from OAuth2Client
Defined in OAuth2Client:938
Type parameters :
  • T

Provides a request implementation with OAuth 2.0 flow. If credentials have a refresh_token, in cases of HTTP 401 and 403 responses, it automatically asks for a new access token and replays the unsuccessful request.

Parameters :
Name Type Optional Description
opts GaxiosOptions No

Request options.

Returns : GaxiosPromise<T>

Request object

revokeCredentials
revokeCredentials()
Inherited from OAuth2Client
Defined in OAuth2Client:906

Revokes access token and clears the credentials object

Returns : GaxiosPromise<RevokeCredentialsResult>
revokeToken
revokeToken(token: string)
Inherited from OAuth2Client
Defined in OAuth2Client:880

Revokes the access given to token.

Parameters :
Name Type Optional Description
token string No

The existing token to be revoked.

Returns : GaxiosPromise<RevokeCredentialsResult>
verifyIdToken
verifyIdToken(options: VerifyIdTokenOptions)
Inherited from OAuth2Client
Defined in OAuth2Client:1039

Verify id token is token by checking the certs and audience

Parameters :
Name Type Optional Description
options VerifyIdTokenOptions No

that contains all options.

verifySignedJwtWithCerts
verifySignedJwtWithCerts()
Inherited from OAuth2Client
Defined in OAuth2Client:1236
Returns : void
Async verifySignedJwtWithCertsAsync
verifySignedJwtWithCertsAsync(jwt: string, certs: Certificates | PublicKeys, requiredAudience?: string | string[], issuers?: string[], maxExpiry?: number)
Inherited from OAuth2Client
Defined in OAuth2Client:1254

Verify the id token is signed with the correct certificate and is from the correct audience.

Parameters :
Name Type Optional Description
jwt string No

The jwt to verify (The ID Token in this case).

certs Certificates | PublicKeys No

The array of certs to test the jwt against.

requiredAudience string | string[] Yes

The audience to test the jwt against.

issuers string[] Yes

The allowed issuers of the jwt (Optional).

maxExpiry number Yes

The max expiry the certificate can be (Optional).

Returns : unknown

Returns a promise resolving to LoginTicket on verification.

import arrify = require('arrify');
import {GaxiosError} from 'gaxios';
import * as gcpMetadata from 'gcp-metadata';

import {CredentialRequest, Credentials} from './credentials';
import {GetTokenResponse, OAuth2Client, RefreshOptions} from './oauth2client';

export interface ComputeOptions extends RefreshOptions {
  /**
   * The service account email to use, or 'default'. A Compute Engine instance
   * may have multiple service accounts.
   */
  serviceAccountEmail?: string;
  /**
   * The scopes that will be requested when acquiring service account
   * credentials. Only applicable to modern App Engine and Cloud Function
   * runtimes as of March 2019.
   */
  scopes?: string | string[];
}

export class Compute extends OAuth2Client {
  private serviceAccountEmail: string;
  scopes: string[];

  /**
   * Google Compute Engine service account credentials.
   *
   * Retrieve access token from the metadata server.
   * See: https://developers.google.com/compute/docs/authentication
   */
  constructor(options: ComputeOptions = {}) {
    super(options);
    // Start with an expired refresh token, which will automatically be
    // refreshed before the first API call is made.
    this.credentials = {expiry_date: 1, refresh_token: 'compute-placeholder'};
    this.serviceAccountEmail = options.serviceAccountEmail || 'default';
    this.scopes = arrify(options.scopes);
  }

  /**
   * Refreshes the access token.
   * @param refreshToken Unused parameter
   */
  protected async refreshTokenNoCache(
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    refreshToken?: string | null
  ): Promise<GetTokenResponse> {
    const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`;
    let data: CredentialRequest;
    try {
      const instanceOptions: gcpMetadata.Options = {
        property: tokenPath,
      };
      if (this.scopes.length > 0) {
        instanceOptions.params = {
          scopes: this.scopes.join(','),
        };
      }
      data = await gcpMetadata.instance(instanceOptions);
    } catch (e) {
      if (e instanceof GaxiosError) {
        e.message = `Could not refresh access token: ${e.message}`;
        this.wrapError(e);
      }

      throw e;
    }
    const tokens = data as Credentials;
    if (data && data.expires_in) {
      tokens.expiry_date = new Date().getTime() + data.expires_in * 1000;
      delete (tokens as CredentialRequest).expires_in;
    }
    this.emit('tokens', tokens);
    return {tokens, res: null};
  }

  /**
   * Fetches an ID token.
   * @param targetAudience the audience for the fetched ID token.
   */
  async fetchIdToken(targetAudience: string): Promise<string> {
    const idTokenPath =
      `service-accounts/${this.serviceAccountEmail}/identity` +
      `?format=full&audience=${targetAudience}`;
    let idToken: string;
    try {
      const instanceOptions: gcpMetadata.Options = {
        property: idTokenPath,
      };
      idToken = await gcpMetadata.instance(instanceOptions);
    } catch (e) {
      if (e instanceof Error) {
        e.message = `Could not fetch ID token: ${e.message}`;
      }

      throw e;
    }

    return idToken;
  }

  protected wrapError(e: GaxiosError) {
    const res = e.response;
    if (res && res.status) {
      e.code = res.status.toString();
      if (res.status === 403) {
        e.message =
          'A Forbidden error was returned while attempting to retrieve an access ' +
          'token for the Compute Engine built-in service account. This may be because the Compute ' +
          'Engine instance does not have the correct permission scopes specified: ' +
          e.message;
      } else if (res.status === 404) {
        e.message =
          'A Not Found error was returned while attempting to retrieve an access' +
          'token for the Compute Engine built-in service account. This may be because the Compute ' +
          'Engine instance does not have any permission scopes specified: ' +
          e.message;
      }
    }
  }
}

results matching ""

    No results matching ""