问题描述
因此,我想在API中进行一些路由,这些路由将根据在MongoDB中定义的用户角色显示不同的数据.这是我现在拥有的示例,它可以正常工作...
So I'd like to make some routes in an API that will show different data based on the user role, defined in MongoDB. Here's a sampling of what I have right now, it works...
router.get('/test', passport.authenticate('bearer', {session: false}), function (req, res) {
if (req.user.role == "premium") {
return res.send('you can see this content');
}
else {
return res.send('you can not see this content');
}
})
但是,最终目标是向用户提供至少内容,即使用户未登录或没有使用正确的角色进行身份验证.
However, the end goal is to present at least something to the user, even if they're not logged in or authenticated with the right kind of role.
router.get('/test', passport.authenticate('bearer', {session: false}), function (req, res) {
if (req.user.role == "premium") {
return res.send('this is premium content');
}
else {
// could be hit by another role, or no user at all
return res.send([some truncated version of the premium content]);
}
})
我想我会找出方法,但是我不知道如何指定在请求中没有任何Authorization标头的情况下可能会被击中的相同路由.
Which I would think I'd figure out how to work, but I don't know how to specify the same route which possibly could be hit without any Authorization header in the request.
在Passport.js/Express中可以吗?
Is this possible in Passport.js/Express?
推荐答案
我建议您使用HTTP状态代码和错误对象,这是一种常见的API约定,它使您的API用户可以了解正在发生的事情以及原因:
I would suggest that you use HTTP status codes and an error object, this is a common API convention and it allows your API users to know what's happening and why:
app.get('/premium-resource', function(req, res, next) {
passport.authenticate('bearer', function(err, user) {
if (user){
if (user.role === 'premium'){
return res.send(200,{userContent:'you are a premium user'});
}else{
return res.send(403,{
'status': 403,
'code': 1, // custom code that makes sense for your application
'message': 'You are not a premium user',
'moreInfo': 'https://myawesomeapi.io/upgrade'
});
}
}else{
return res.send(401,{
'status': 401,
'code': 2, // custom code that makes sense for your application
'message': 'You are not authenticated.',
'moreInfo': 'https://myawesomeapi.io/docs'
});
}
})(req, res, next);
});
免责声明:我在 Stormpath 工作,我们在API身份验证和设计方面投入了很多思想,我们做了一个非常真实的演示关于主题:
Disclaimer: I work at Stormpath and we put a lot of thought into API authentication and design, we have a really presentation on the topic:
https://stormpath.com/blog/designing-rest-json-apis/
这篇关于验证角色和Passport.js进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!