Skip to content

Instantly share code, notes, and snippets.

@micimize
Last active April 13, 2020 16:00
Show Gist options
  • Save micimize/d97de5de0ef0a69d3adb9cdab3a6d4ad to your computer and use it in GitHub Desktop.
Save micimize/d97de5de0ef0a69d3adb9cdab3a6d4ad to your computer and use it in GitHub Desktop.
express middleware for verifying and decoding google jwt tokens
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),
)
/* */
@rublev
Copy link

rublev commented Apr 9, 2020

been 6mo, any issues with this so far?

@micimize
Copy link
Author

@rublev none so far

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment