/
verifier.js
52 lines (48 loc) · 1.59 KB
/
verifier.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"use strict";
const { OAuth2Client } = require("google-auth-library");
const debug = require("debug")("koa-gcp-iap:verifier");
class Verifier {
constructor({ projectNumber, projectId, backendServiceId }) {
this.expectedAudience = null;
if (projectNumber && projectId) {
// Expected Audience for App Engine.
this.expectedAudience = `/projects/${projectNumber}/apps/${projectId}`;
} else if (projectNumber && backendServiceId) {
// Expected Audience for Compute Engine
this.expectedAudience = `/projects/${projectNumber}/global/backendServices/${backendServiceId}`;
} else {
throw new Error("invalid argument");
}
this.oAuth2Client = new OAuth2Client();
debug("initialized successfully");
}
/**
* Verify the ID token from IAP
* @see https://cloud.google.com/iap/docs/signed-headers-howto
*/
async verify(iapJwt) {
if (typeof iapJwt !== "string") {
debug(`auth failed(iapJwt is invalid: '${iapJwt}')`);
throw new Error("iapJwt must be string");
}
try {
// Verify the id_token, and access the claims.
debug("start getIapPublicKeys()");
const response = await this.oAuth2Client.getIapPublicKeys();
debug("end getIapPublicKeys()");
const ticket = await this.oAuth2Client.verifySignedJwtWithCertsAsync(
iapJwt,
response.pubkeys,
this.expectedAudience,
["https://cloud.google.com/iap"]
);
debug("auth success!");
debug(`ticket: ${ticket}`);
return ticket;
} catch (e) {
debug(e);
throw e;
}
}
}
module.exports = Verifier;