src/auth/idtokenclient.ts
Properties |
fetchIdToken |
fetchIdToken:
|
Type : function
|
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;
}
}
}