Skip to content

Commit 0aa7f8f

Browse files
save file
1 parent 23a31f3 commit 0aa7f8f

File tree

1 file changed

+12
-13
lines changed
  • utils/gcloud/generate-token-from-service-account-keyfile

1 file changed

+12
-13
lines changed

utils/gcloud/generate-token-from-service-account-keyfile/generate.js

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11

22

33

4-
async function generate(keyfile){
4+
async function generate(keyfile,scope){
55

66

77

88
var clientEmail = keyfile.client_email;
99
var privateKeyPem = keyfile.private_key.replace(/\\n/g,'\n');
10-
var scope = 'https://www.googleapis.com/auth/devstorage.read_write';
1110

1211
var assertion = await buildJwtAssertion({clientEmail,privateKeyPem,scope});
1312
var json = await exchangeForAccessToken(assertion);
@@ -83,24 +82,24 @@
8382
}//sign
8483

8584

86-
async function buildJwtAssertion({clientEmail,privateKeyPem,scope,aud='https://oauth2.googleapis.com/token'}){
85+
async function buildJwtAssertion({clientEmail,privateKeyPem,scope,aud}){
8786

88-
var key = await importPkcs8PrivateKey(privateKeyPem);
89-
87+
scope = Array.isArray(scope) ? scope.join(' ') : scope;
88+
aud ||= 'https://oauth2.googleapis.com/token';
89+
9090
var now = Math.floor(Date.now()/1000);
91-
var header = {alg:'RS256',typ:'JWT'};
92-
var payload = {
93-
iss : clientEmail,
94-
scope : Array.isArray(scope) ? scope.join(' ') : scope,
95-
aud : aud,
96-
iat : now,
97-
exp : now+3600, // 1 hour max
98-
};
91+
92+
var iss = clientEmail;
93+
var iat = now;
94+
var exp = now+3600;
95+
var payload = {iss,scope,aud,iat,exp};
9996

97+
var header = {alg:'RS256',typ:'JWT'};
10098
var encodedHeader = base64url(JSON.stringify(header));
10199
var encodedPayload = base64url(JSON.stringify(payload));
102100
var unsigned = `${encodedHeader}.${encodedPayload}`;
103101

102+
var key = await importPkcs8PrivateKey(privateKeyPem);
104103
var sig = await signRS256(key,unsigned);
105104
var encodedSig = base64url(sig);
106105
var str = `${unsigned}.${encodedSig}`;

0 commit comments

Comments
 (0)