async function getAccessTokenFromServiceAccount(
serviceAccountKey,
{
scope = "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/cloud-platform"
} = {}
) {
if (typeof serviceAccountKey === "string") {
serviceAccountKey = JSON.parse(serviceAccountKey);
}
const tNow = Math.floor(new Date().getTime() / 1000);
const sHeader = JSON.stringify({ alg: "RS256", typ: "JWT" });
const sPayload = JSON.stringify({
iss: serviceAccountKey.client_email,
scope: scope,
iat: tNow,
exp: tNow + 600,
aud: "https://oauth2.googleapis.com/token"
});
const JWT = jsrsasign.KJUR.jws.JWS.sign(
"RS256",
sHeader,
sPayload,
serviceAccountKey.private_key
);
const tokenResponse = await fetch("https://oauth2.googleapis.com/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: `grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=${JWT}`
});
if (tokenResponse.status != 200) {
throw new Error(await tokenResponse.text());
}
return (await tokenResponse.json()).access_token;
}