UNPKG

2.09 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 access token from the metadata server.
23 * See: https://developers.google.com/compute/docs/authentication
24 */
25 constructor(options) {
26 super();
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 || 0) < Date.now()) {
35 const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience);
36 this.credentials = {
37 id_token: idToken,
38 expiry_date: this.getIdTokenExpiryDate(idToken),
39 };
40 }
41 const headers = {
42 Authorization: 'Bearer ' + this.credentials.id_token,
43 };
44 return { headers };
45 }
46 getIdTokenExpiryDate(idToken) {
47 const payloadB64 = idToken.split('.')[1];
48 if (payloadB64) {
49 const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('ascii'));
50 return payload.exp * 1000;
51 }
52 }
53}
54exports.IdTokenClient = IdTokenClient;
55//# sourceMappingURL=idtokenclient.js.map
\No newline at end of file