使用护照持有人的自定义错误消息 [英] Custom Error message using passport Bearer

查看:67
本文介绍了使用护照持有人的自定义错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用护照保护我的API.我有点难以理解我应该如何在出现错误的情况下发回自定义消息,并且希望在这里找到答案.

这就是我所做的:

路由(server.js):

  router.route('/Applications').get(authController.BearerAuthenticated,applicationController.getApplications); 

我的护照资料(authController.js):

  Passport.use(new BearerStrategy(function(token,cb){Token.findOne({令牌:令牌},功能(ERR,令牌){if(err){返回cb(null,false);}如果(!token){返回cb(null,false);}返回cb(null,令牌);});}));Exports.BearerAuthenticated = Passport.authenticate('bearer',{session:false}); 

我的应用程序方法(Application.js)

  exports.getApplications = function(req,res){Application.find({userId:req.user._id},function(err,apps){如果(错误)res.send(err);res.json(apps);});}; 

如果我的令牌有效,并且Bearer方法返回

 返回cb(null,令牌); 

然后,我可以输入我的getApplications方法.这是有道理的.

问题是当令牌无效时,我不输入方法(也很有意义),但我想不出一种向客户返回自定义消息的方法,而不是我得到的以下消息默认.

<预> <代码>未经授权

返回带有错误代码的Json来正确地让用户知道他的令牌已失效或根本不存在的方法是什么?

谢谢您的时间.:)

解决方案

您可以在 authenticate 中传递回调并从那里处理错误.请注意,在这种情况下,您必须手动执行默认操作,例如用户登录等.有关更多信息,请参见 解决方案

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)
}

这篇关于使用护照持有人的自定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆