Skip to content

Instantly share code, notes, and snippets.

@thebigredgeek
Last active May 18, 2020
Embed
What would you like to do?
JWT Protected Endpoint
const verifyJWT = async (req, res, next) => {
// Extract the authorization header
const header = req.get('Authorization');
// If no authorization header is present,
// send back an error
if (!header) {
res.status(401).send({
message: "Authorization required"
});
return false;
}
// Let's assume the token is sent using
// the standard Bearer <token> schema.
// In this case, we need to extract the
// <token> portion of the string by
// splitting it on the space between
// it and Bearer.
const token = header.split(' ')[1];
// If there is not token, this a malformed
// authentication header so we need to send
// back an error message.
if (!token) {
res.status(400).send({
message: 'Authentication header must be Bearer <token> format'
});
return false;
}
// Verify the JWT and
// extract the user id
// from it
const [err, { id }] = await to(jwt.verify(token, JWT_SECRET));
// If the JWT is invalid,
// send back an error message
if (err) {
res.status(401).send({
message: 'Invalid JWT token'
});
return false;
}
req.userId = id;
if (next) {
return next();
}
return true;
};
// Apply the verifyJWT middleware before calling
// the request handler
app.get('/user/me', verifyJWT, async (req, res) => {
// Get the user by the id attached
// to the request object by the
// verify jwt middleware
const myUser = await to(model.getUserById(req.userId));
// Return my user :)
return res.status(200).send(myUser);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment