Last active
April 13, 2020 16:00
-
-
Save micimize/d97de5de0ef0a69d3adb9cdab3a6d4ad to your computer and use it in GitHub Desktop.
express middleware for verifying and decoding google jwt tokens
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { OAuth2Client } = require('google-auth-library'); | |
function decodedTokenToUser({ | |
// protocole concerns | |
iss, | |
azp, | |
aud, | |
at_hash, | |
iat, | |
exp, | |
// actual user info | |
sub: id, | |
email, | |
email_verified, | |
name, | |
picture, | |
given_name, | |
family_name, | |
locale, | |
}){ | |
return { | |
id, | |
email, | |
email_verified, | |
name, | |
picture, | |
given_name, | |
family_name, | |
locale, | |
} | |
} | |
function verifier(client_id) { | |
const client = new OAuth2Client(client_id); | |
async function verifyAndDecode(token) { | |
const ticket = await client.verifyIdToken({ | |
idToken: token, | |
audience: client_id, | |
}); | |
return ticket.getPayload(); | |
} | |
return verifyAndDecode | |
} | |
module.exports = client_id => { | |
verify = verifier(client_id) | |
return async (request, response, next) => { | |
const auth_header = request.get('Authorization') | |
const unauthorized = body => response.status(401).send(body) | |
if (!auth_header || !auth_header.match(/^Bearer\s/)) { | |
return unauthorized('missing authorization header') | |
} | |
const token = auth_header.replace(/^Bearer\s/, '') | |
try { | |
const payload = await verify(token) | |
request.user = decodedTokenToUser(payload) | |
next() | |
} catch (err) { | |
return unauthorized(err) | |
} | |
} | |
} | |
/* USAGE * | |
app.use( | |
'/authenticated', | |
googleJWT(GOOGLE_CLIENT_IDS), | |
) | |
/* */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
been 6mo, any issues with this so far?