Skip to content

Instantly share code, notes, and snippets.

@janneh
Last active November 29, 2016 10:52
Show Gist options
  • Save janneh/7044bef43f6d825aacc7cac377cd7e9d to your computer and use it in GitHub Desktop.
Save janneh/7044bef43f6d825aacc7cac377cd7e9d to your computer and use it in GitHub Desktop.
Auth middleware for JWT:s
// `jwt` is the encoded JSON Web Token
// `token` is the decoded jwt
// jwtFromRequest(req: Request): String
// algorithmFromToken(token: Object): String
// keyFromToken(token: Object): Promise<key: string>
const auth = fucntion({ jwtFromRequest, keyFromToken, algorithmFromToken }) {
return (req, res, next) => {
const jwt = jwtFromRequest(req)
const token = jws.decode(jwt)
if (!token) next(new Error("Unauthorized"))
keyFromToken(token)
.then(key => {
if (jws.verify(jwt, algorithmFromToken(token), key)) {
// should check expiry and make refresh here
next()
} else {
next(new Error("Unauthorized"))
}
})
.catch(error => {
console.error(error)
next(new Error("Unauthorized"))
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment