I'm using passport to secure my API. I kind of struggle to understand how i'm supposed to send back custom message in case of error and i'm hoping to find an answer here.
Here is what i did:
A route (server.js):
router.route('/Applications').get(authController.BearerAuthenticated, applicationController.getApplications);
My Passport Stuff (authController.js):
Passport.use(new BearerStrategy(function(token, cb) {
Token.findOne({token: token}, function(err, token){
if (err){return cb(null, false);}
if (!token) { return cb(null, false); }
return cb(null, token);
});
}));
exports.BearerAuthenticated = Passport.authenticate('bearer', {session: false});
My Application method (Application.js)
exports.getApplications = function(req, res) {
Application.find({userId:req.user._id}, function(err, apps) {
if (err)
res.send(err);
res.json(apps);
});
};
If my token is valid and the Bearer method return
return cb(null, token);
Then i can enter my getApplications method. It makes sense.
The thing is when the token is not valid, i don't enter the method (makes sense too) but i can't figure out a way to return a custom message to the client instead of the following message i get by default.
Unauthorized
What would be a way to return a Json with an error code to properly let the user know that his token is dead or simply does not exist ?
Thanks for you time. :)
You can pass a callback in
authenticate
and handle errors from there. Note that in this case you have to manually perform the default operations like user login etc. More on it in here.