Custom Error message using passport Bearer

2019-06-16 16:10发布

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. :)

1条回答
三岁会撩人
2楼-- · 2019-06-16 16:46

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.

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)
}
查看更多
登录 后发表回答