File

src/auth/impersonated.ts

Extends

OAuth2Client

Index

Properties
Methods

Constructor

constructor(options: ImpersonatedOptions)

Impersonated service account credentials.

Create a new access token by impersonating another service account.

Impersonated Credentials allowing credentials issued to a user or service account to impersonate another. The source project using Impersonated Credentials must enable the "IAMCredentials" API. Also, the target service account must grant the orginating principal the "Service Account Token Creator" IAM role.

acquire the impersonated credentials. impersonate. required to grant the final access_token. If set, the sequence of identities must have "Service Account Token Creator" capability granted to the preceding identity. For example, if set to [serviceAccountB, serviceAccountC], the sourceCredential must have the Token Creator role on serviceAccountB. serviceAccountB must have the Token Creator on serviceAccountC. Finally, C must have Token Creator on target_principal. If left unset, sourceCredential must have that role on targetPrincipal. authorization grant. credential should be valid for up to 3600 seconds by default, or 43,200 seconds by extending the token's lifetime, see: https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth

Parameters :
Name Type Optional Description
options ImpersonatedOptions No
  • The configuration object.

Properties

Optional _clientId
Type : string
Inherited from OAuth2Client
Defined in OAuth2Client:417
Optional _clientSecret
Type : string
Inherited from OAuth2Client
Defined in OAuth2Client:420
Optional apiKey
Type : string
Inherited from OAuth2Client
Defined in OAuth2Client:422
eagerRefreshThresholdMillis
Type : number
Inherited from OAuth2Client
Defined in OAuth2Client:426
forceRefreshOnFailure
Type : boolean
Inherited from OAuth2Client
Defined in OAuth2Client:428
Optional projectId
Type : string
Inherited from OAuth2Client
Defined in OAuth2Client:424

Methods

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

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

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/master/samples/oauth2-codeVerifier.js

getAccessToken
getAccessToken(callback?: GetAccessTokenCallback)
Inherited from OAuth2Client
Defined in OAuth2Client:734
Parameters :
Name Type Optional
callback GetAccessTokenCallback Yes
Returns : Promise | void
getFederatedSignonCerts
getFederatedSignonCerts(callback?: GetFederatedSignonCertsCallback)
Inherited from OAuth2Client
Defined in OAuth2Client:1049
Parameters :
Name Type Optional
callback GetFederatedSignonCertsCallback Yes
Returns : Promise | void
Async getFederatedSignonCertsAsync
getFederatedSignonCertsAsync()
Inherited from OAuth2Client
Defined in OAuth2Client:1062
getIapPublicKeys
getIapPublicKeys(callback?: GetIapPublicKeysCallback)
Inherited from OAuth2Client
Defined in OAuth2Client:1134
Parameters :
Name Type Optional
callback GetIapPublicKeysCallback Yes
Returns : Promise | void
Async getIapPublicKeysAsync
getIapPublicKeysAsync()
Inherited from OAuth2Client
Defined in OAuth2Client:1147
Returns : Promise<IapPublicKeysResponse>
Async getRequestHeaders
getRequestHeaders(url?: string)
Inherited from OAuth2Client
Defined in OAuth2Client:774

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

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(codeOrOptions: string | GetTokenOptions, callback?: GetTokenCallback)
Inherited from OAuth2Client
Defined in OAuth2Client:592
Parameters :
Name Type Optional
codeOrOptions string | GetTokenOptions No
callback GetTokenCallback Yes
Returns : Promise | void
Async getTokenInfo
getTokenInfo(accessToken: string)
Inherited from OAuth2Client
Defined in OAuth2Client:1020

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(callback: RefreshAccessTokenCallback)
Inherited from OAuth2Client
Defined in OAuth2Client:705
Parameters :
Name Type Optional
callback RefreshAccessTokenCallback No
Returns : void
request
request(opts: GaxiosOptions, callback?: BodyResponseCallback<T>)
Inherited from OAuth2Client
Defined in OAuth2Client:899
Type parameters :
  • T
Parameters :
Name Type Optional
opts GaxiosOptions No
callback BodyResponseCallback<T> Yes
Returns : GaxiosPromise | void
revokeCredentials
revokeCredentials()
Inherited from OAuth2Client
Defined in OAuth2Client:865

Revokes access token and clears the credentials object

Returns : GaxiosPromise<RevokeCredentialsResult>
revokeToken
revokeToken(token: string, callback?: BodyResponseCallback)
Inherited from OAuth2Client
Defined in OAuth2Client:844
Parameters :
Name Type Optional
token string No
callback BodyResponseCallback<RevokeCredentialsResult> Yes
Returns : GaxiosPromise | void
verifyIdToken
verifyIdToken(options: VerifyIdTokenOptions, callback?: (err?: Error | null,login?: LoginTicket) => void)
Inherited from OAuth2Client
Defined in OAuth2Client:975
Parameters :
Name Type Optional
options VerifyIdTokenOptions No
callback function Yes
Returns : void | Promise
verifySignedJwtWithCerts
verifySignedJwtWithCerts()
Inherited from OAuth2Client
Defined in OAuth2Client:1161
Returns : void
Async verifySignedJwtWithCertsAsync
verifySignedJwtWithCertsAsync(jwt: string, certs: Certificates | PublicKeys, requiredAudience?: string | string[], issuers?: string[], maxExpiry?: number)
Inherited from OAuth2Client
Defined in OAuth2Client:1179

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 {GetTokenResponse, OAuth2Client, RefreshOptions} from './oauth2client';
import {AuthClient} from './authclient';

export interface ImpersonatedOptions extends RefreshOptions {
  /**
   * Client used to perform exchange for impersonated client.
   */
  sourceClient?: AuthClient;
  /**
   * The service account to impersonate.
   */
  targetPrincipal?: string;
  /**
   * Scopes to request during the authorization grant.
   */
  targetScopes?: string[];
  /**
   * The chained list of delegates required to grant the final access_token.
   */
  delegates?: string[];
  /**
   * Number of seconds the delegated credential should be valid.
   */
  lifetime?: number | 3600;
  /**
   * API endpoint to fetch token from.
   */
  endpoint?: string;
}

export interface TokenResponse {
  accessToken: string;
  expireTime: string;
}

export class Impersonated extends OAuth2Client {
  private sourceClient: AuthClient;
  private targetPrincipal: string;
  private targetScopes: string[];
  private delegates: string[];
  private lifetime: number;
  private endpoint: string;

  /**
   * Impersonated service account credentials.
   *
   * Create a new access token by impersonating another service account.
   *
   * Impersonated Credentials allowing credentials issued to a user or
   * service account to impersonate another. The source project using
   * Impersonated Credentials must enable the "IAMCredentials" API.
   * Also, the target service account must grant the orginating principal
   * the "Service Account Token Creator" IAM role.
   *
   * @param {object} options - The configuration object.
   * @param {object} [options.sourceClient] the source credential used as to
   * acquire the impersonated credentials.
   * @param {string} [options.targetPrincipal] the service account to
   * impersonate.
   * @param {string[]} [options.delegates] the chained list of delegates
   * required to grant the final access_token. If set, the sequence of
   * identities must have "Service Account Token Creator" capability granted to
   * the preceding identity. For example, if set to [serviceAccountB,
   * serviceAccountC], the sourceCredential must have the Token Creator role on
   * serviceAccountB. serviceAccountB must have the Token Creator on
   * serviceAccountC. Finally, C must have Token Creator on target_principal.
   * If left unset, sourceCredential must have that role on targetPrincipal.
   * @param {string[]} [options.targetScopes] scopes to request during the
   * authorization grant.
   * @param {number} [options.lifetime] number of seconds the delegated
   * credential should be valid for up to 3600 seconds by default, or 43,200
   * seconds by extending the token's lifetime, see:
   * https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth
   * @param {string} [options.endpoint] api endpoint override.
   */
  constructor(options: ImpersonatedOptions = {}) {
    super(options);
    this.credentials = {
      expiry_date: 1,
      refresh_token: 'impersonated-placeholder',
    };
    this.sourceClient = options.sourceClient ?? new OAuth2Client();
    this.targetPrincipal = options.targetPrincipal ?? '';
    this.delegates = options.delegates ?? [];
    this.targetScopes = options.targetScopes ?? [];
    this.lifetime = options.lifetime ?? 3600;
    this.endpoint = options.endpoint ?? 'https://iamcredentials.googleapis.com';
  }

  /**
   * Refreshes the access token.
   * @param refreshToken Unused parameter
   */
  protected async refreshToken(
    refreshToken?: string | null
  ): Promise<GetTokenResponse> {
    try {
      await this.sourceClient.getAccessToken();
      const name = 'projects/-/serviceAccounts/' + this.targetPrincipal;
      const u = `${this.endpoint}/v1/${name}:generateAccessToken`;
      const body = {
        delegates: this.delegates,
        scope: this.targetScopes,
        lifetime: this.lifetime + 's',
      };
      const res = await this.sourceClient.request<TokenResponse>({
        url: u,
        data: body,
        method: 'POST',
      });
      const tokenResponse = res.data;
      this.credentials.access_token = tokenResponse.accessToken;
      this.credentials.expiry_date = Date.parse(tokenResponse.expireTime);
      return {
        tokens: this.credentials,
        res,
      };
    } catch (error) {
      const status = error?.response?.data?.error?.status;
      const message = error?.response?.data?.error?.message;
      if (status && message) {
        error.message = `${status}: unable to impersonate: ${message}`;
        throw error;
      } else {
        error.message = `unable to impersonate: ${error}`;
        throw error;
      }
    }
  }
}

result-matching ""

    No results matching ""