Skip to content

Instantly share code, notes, and snippets.

@ramsaylanier
Last active February 1, 2018 19:37
Show Gist options
  • Save ramsaylanier/7d5f255083e8493a90a9eb6fd6823c92 to your computer and use it in GitHub Desktop.
Save ramsaylanier/7d5f255083e8493a90a9eb6fd6823c92 to your computer and use it in GitHub Desktop.
const expressJwt = require('express-jwt')
const jwksRsa = require('jwks-rsa')
const jwt = require('jsonwebtoken')
const jwksOptions = {
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 1,
jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`
}
const jwks = jwksRsa(jwksOptions)
// checks the incoming authorization token
const checkJwt = expressJwt({
secret: jwksRsa.expressJwtSecret(jwksOptions),
credentialsRequired: false,
audience: process.env.AUTH0_AUDIENCE,
issuer: process.env.AUTH0_ISSUER,
algorithms: [`RS256`]
})
// validates the idToken from Auth0 when calling the authentication mutation and returns a decoded idToken
// for creating a new Prisma user
const validateAndParseIdToken = (idToken) => new Promise((resolve, reject) => {
const { header, payload} = jwt.decode(idToken, {complete: true})
if (!header || !header.kid || !payload) reject(new Error('Invalid Token'))
jwks.getSigningKey(header.kid, (err, key) => {
if (err) reject(new Error('Error getting signing key: ' + err.message))
jwt.verify(idToken, key.publicKey, { algorithms: ['RS256'] }, (err, decoded) => {
if (err) reject('jwt verify error: ' + err.message)
resolve(decoded)
})
})
})
module.exports = { checkJwt, validateAndParseIdToken }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment