Skip to content

Instantly share code, notes, and snippets.

@glutengo
Last active April 12, 2017 22:03
Show Gist options
  • Select an option

  • Save glutengo/4ad46c5d01e5567e54af49e0d0935e8e to your computer and use it in GitHub Desktop.

Select an option

Save glutengo/4ad46c5d01e5567e54af49e0d0935e8e to your computer and use it in GitHub Desktop.
Middleware for private endpoints
app.use(function(req, res, next){
//check header or url parameters or post parameters for token
var token = req.body.token || req.query['token'] || req.headers['x-access-token'];
//decode token
if(token){
//verifiy secret
jwt.verify(token, config.SECRET, function(err, decoded){
if(err){
return res.status(401).send({
message: 'Failed to authenticate token.'
});
} else{
//if everything is good, save to request for use in other reoutes
req.user = decoded;
next();
}
})
} else {
//if there is no token
//return an HTTP response of 403 (access forbidden ) and an error message
return res.status(403).send({
message: 'No token provided.'
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment