Custom error message using passport sign

I use a passport to protect my API. Iโ€™m kind of struggling to understand how I should send back a custom message in case of an error, and I hope to find an answer here.

Here is what I did:

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 returns

 return cb(null, token); 

Then I can introduce the getApplications method. It makes sense.

The fact is that the token is invalid, I donโ€™t enter the method (it makes sense too), but I canโ€™t understand how to return the user message to the client instead of the next message that I get by default.

 Unauthorized 

How can I return Json with an error code so that it correctly informs the user that his token is dead or simply does not exist?

Thank you for your time.:)

+7
source share
1 answer

You can pass the callback to authenticate and handle the errors from there. Please note that in this case you will have to manually perform default operations, such as user login, etc. More about this in here .

 exports.BearerAuthenticated = function(req, res, next){ passport.authenticate('bearer', {session: false}, function(err, user, info) { if (err) { return next(err); } //authentication error if (!user) { return res.json({error: info.message || 'Invalid Token'}) } //success req.logIn(user, function(err) { if (err) { return next(err); } return next(); }); })(req, res, next) } 
+8
source

All Articles