UNPKG

2.08 kBJavaScriptView Raw
1"use strict";
2// Copyright 2020 Google LLC
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15Object.defineProperty(exports, "__esModule", { value: true });
16exports.IdTokenClient = void 0;
17const oauth2client_1 = require("./oauth2client");
18class IdTokenClient extends oauth2client_1.OAuth2Client {
19 /**
20 * Google ID Token client
21 *
22 * Retrieve ID token from the metadata server.
23 * See: https://cloud.google.com/docs/authentication/get-id-token#metadata-server
24 */
25 constructor(options) {
26 super(options);
27 this.targetAudience = options.targetAudience;
28 this.idTokenProvider = options.idTokenProvider;
29 }
30 async getRequestMetadataAsync(
31 // eslint-disable-next-line @typescript-eslint/no-unused-vars
32 url) {
33 if (!this.credentials.id_token ||
34 !this.credentials.expiry_date ||
35 this.isTokenExpiring()) {
36 const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience);
37 this.credentials = {
38 id_token: idToken,
39 expiry_date: this.getIdTokenExpiryDate(idToken),
40 };
41 }
42 const headers = {
43 Authorization: 'Bearer ' + this.credentials.id_token,
44 };
45 return { headers };
46 }
47 getIdTokenExpiryDate(idToken) {
48 const payloadB64 = idToken.split('.')[1];
49 if (payloadB64) {
50 const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('ascii'));
51 return payload.exp * 1000;
52 }
53 }
54}
55exports.IdTokenClient = IdTokenClient;