File

src/auth/idtokenclient.ts

Extends

OAuth2Client

Index

Properties
Methods

Constructor

constructor(options: IdTokenOptions)

Google ID Token client

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

Parameters :
Name Type Optional
options IdTokenOptions No

Properties

idTokenProvider
Type : IdTokenProvider
targetAudience
Type : string
Optional _clientId
Type : string
Inherited from OAuth2Client
Defined in OAuth2Client:434
Optional _clientSecret
Type : string
Inherited from OAuth2Client
Defined in OAuth2Client:437
Optional apiKey
Type : string
Inherited from OAuth2Client
Defined in OAuth2Client:439
eagerRefreshThresholdMillis
Type : number
Inherited from OAuth2Client
Defined in OAuth2Client:443
forceRefreshOnFailure
Type : boolean
Inherited from OAuth2Client
Defined in OAuth2Client:445
Optional projectId
Type : string
Inherited from OAuth2Client
Defined in OAuth2Client:441
Optional refreshHandler
Type : GetRefreshHandlerCallback
Inherited from OAuth2Client
Defined in OAuth2Client:447

Methods

generateAuthUrl
generateAuthUrl(opts: GenerateAuthUrlOpts)
Inherited from OAuth2Client
Defined in OAuth2Client:541

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:562
Returns : void
Async generateCodeVerifierAsync
generateCodeVerifierAsync()
Inherited from OAuth2Client
Defined in OAuth2Client:578

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:765

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

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

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:1154
getIapPublicKeys
getIapPublicKeys()
Inherited from OAuth2Client
Defined in OAuth2Client:1227

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:1242
Returns : Promise<IapPublicKeysResponse>
Async getRequestHeaders
getRequestHeaders(url?: string)
Inherited from OAuth2Client
Defined in OAuth2Client:818

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:893

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:607

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:1112

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:737

Retrieves the access token using refresh token

Returns : Promise<RefreshAccessTokenResponse>
request
request(opts: GaxiosOptions)
Inherited from OAuth2Client
Defined in OAuth2Client:961
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:929

Revokes access token and clears the credentials object

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

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:1062

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:1259
Returns : void
Async verifySignedJwtWithCertsAsync
verifySignedJwtWithCertsAsync(jwt: string, certs: Certificates | PublicKeys, requiredAudience?: string | string[], issuers?: string[], maxExpiry?: number)
Inherited from OAuth2Client
Defined in OAuth2Client:1277

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 {Credentials} from './credentials';
import {Headers, OAuth2Client, RequestMetadataResponse} from './oauth2client';

export interface IdTokenOptions {
  /**
   * The client to make the request to fetch an ID token.
   */
  idTokenProvider: IdTokenProvider;
  /**
   * The audience to use when requesting an ID token.
   */
  targetAudience: string;
}

export interface IdTokenProvider {
  fetchIdToken: (targetAudience: string) => Promise<string>;
}

export class IdTokenClient extends OAuth2Client {
  targetAudience: string;
  idTokenProvider: IdTokenProvider;

  /**
   * Google ID Token client
   *
   * Retrieve access token from the metadata server.
   * See: https://developers.google.com/compute/docs/authentication
   */
  constructor(options: IdTokenOptions) {
    super();
    this.targetAudience = options.targetAudience;
    this.idTokenProvider = options.idTokenProvider;
  }

  protected async getRequestMetadataAsync(
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    url?: string | null
  ): Promise<RequestMetadataResponse> {
    if (
      !this.credentials.id_token ||
      (this.credentials.expiry_date || 0) < Date.now()
    ) {
      const idToken = await this.idTokenProvider.fetchIdToken(
        this.targetAudience
      );
      this.credentials = {
        id_token: idToken,
        expiry_date: this.getIdTokenExpiryDate(idToken),
      } as Credentials;
    }

    const headers: Headers = {
      Authorization: 'Bearer ' + this.credentials.id_token,
    };
    return {headers};
  }

  private getIdTokenExpiryDate(idToken: string): number | void {
    const payloadB64 = idToken.split('.')[1];
    if (payloadB64) {
      const payload = JSON.parse(
        Buffer.from(payloadB64, 'base64').toString('ascii')
      );
      return payload.exp * 1000;
    }
  }
}

results matching ""

    No results matching ""