Skip to content

Instantly share code, notes, and snippets.

@leonmak
Last active May 24, 2021 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonmak/3508f611ad4958bb51855aa545cb2376 to your computer and use it in GitHub Desktop.
Save leonmak/3508f611ad4958bb51855aa545cb2376 to your computer and use it in GitHub Desktop.
chrome extension login id token
// need to use launchWebAuthFlow in chrome extension
// can't use gapi in extension
// https://github.com/google/google-api-javascript-client/issues/64
async function getIdTokenInfo(id_token: string) {
const resp = await fetch(
`https://oauth2.googleapis.com/tokeninfo?id_token=${id_token}`
);
return resp.json();
}
async function login() {
const redirectURI = browser.identity.getRedirectURL();
const { oauth2 } = browser.runtime.getManifest();
const clientId = oauth2.client_id;
const initState = sha256(`${Math.floor(Math.random() * 1024)}`);
const authParams = new URLSearchParams({
response_type: "id_token",
client_id: clientId,
scope: ["openid", "email"].join(" "),
redirect_uri: redirectURI,
state: `${initState}`,
nonce: `${Math.floor(Math.random() * 100)}`,
});
// get oauth2 token
const authURL = `https://accounts.google.com/o/oauth2/auth?${authParams.toString()}`;
const responseUrl = await browser.identity.launchWebAuthFlow({
url: authURL,
interactive: true,
});
// get OIDC + email
const url = new URL(responseUrl);
const urlParams = new URLSearchParams(url.hash.slice(1));
const params: { [k: string]: string } = {};
urlParams.forEach((k, v) => (params[v] = k));
const { state, id_token } = params;
if (state !== initState) {
console.error("state invalid");
return {};
}
try {
const { email, exp } = await getIdTokenInfo(id_token);
const newData = { email, id_token, exp: exp * 1000 }; // change exp to ms
return newData;
} catch (e) {
console.error(e);
return {};
}
}
async function logout() {
await browser.identity.launchWebAuthFlow({
url: 'https://accounts.google.com/logout',
interactive: true,
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment