使用护照 Bearer 的自定义错误消息
Custom Error message using passport Bearer
我正在使用护照来保护我的 API。
我有点难以理解在出现错误时我应该如何发回自定义消息,我希望能在这里找到答案。
这是我所做的:
一条路线(server.js):
router.route('/Applications').get(authController.BearerAuthenticated, applicationController.getApplications);
我的护照资料(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});
我的申请方法(Application.js)
exports.getApplications = function(req, res) {
Application.find({userId:req.user._id}, function(err, apps) {
if (err)
res.send(err);
res.json(apps);
});
};
如果我的令牌有效且 Bearer 方法 return
return cb(null, token);
然后我可以进入我的 getApplications 方法。有道理。
事情是当令牌无效时,我没有输入方法(也有意义)但我想不出一种方法来 return 向客户端发送自定义消息而不是我默认收到以下消息。
Unauthorized
有什么方法可以 return 带有错误代码的 Json 来正确地让用户知道他的令牌已失效或根本不存在?
感谢您的宝贵时间。 :)
您可以在 authenticate
中传递回调并从那里处理错误。请注意,在这种情况下,您必须手动执行默认操作,例如用户登录等。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)
}
我正在使用护照来保护我的 API。 我有点难以理解在出现错误时我应该如何发回自定义消息,我希望能在这里找到答案。
这是我所做的:
一条路线(server.js):
router.route('/Applications').get(authController.BearerAuthenticated, applicationController.getApplications);
我的护照资料(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});
我的申请方法(Application.js)
exports.getApplications = function(req, res) {
Application.find({userId:req.user._id}, function(err, apps) {
if (err)
res.send(err);
res.json(apps);
});
};
如果我的令牌有效且 Bearer 方法 return
return cb(null, token);
然后我可以进入我的 getApplications 方法。有道理。
事情是当令牌无效时,我没有输入方法(也有意义)但我想不出一种方法来 return 向客户端发送自定义消息而不是我默认收到以下消息。
Unauthorized
有什么方法可以 return 带有错误代码的 Json 来正确地让用户知道他的令牌已失效或根本不存在?
感谢您的宝贵时间。 :)
您可以在 authenticate
中传递回调并从那里处理错误。请注意,在这种情况下,您必须手动执行默认操作,例如用户登录等。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)
}