node.js - 使用 Passport.js 验证角色和身份验证

标签 node.js express roles passport.js

所以我想在 API 中创建一些路由,这些路由将根据 MongoDB 中定义的用户角色显示不同的数据。这是我现在拥有的样本,它可以工作......

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

但是,最终目标是至少向用户展示一些东西,即使他们没有登录或使用正确的角色进行身份验证。

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 header 的情况下可能会被命中的相同路由。

这在 Passport.js/Express 中可行吗?

最佳答案

我建议您使用 HTTP 状态代码和错误对象,这是一种常见的 API 约定,它允许您的 API 用户知道发生了什么以及为什么:

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 身份验证和设计进行了很多思考,我们对此主题进行了真正的演示:

https://stormpath.com/blog/designing-rest-json-apis/

关于node.js - 使用 Passport.js 验证角色和身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26895219/

相关文章:

node.js - mongodb 获取最喜欢帖子的用户

javascript - 添加到 Node 中的数组/对象

express - 如何在 nginx 反向代理后面为两个 Web 应用程序提供服务

django - 设计基于 Django Rest Framework 角色的授权

node.js - 抛出新的 TypeError ('Router.use()requires a middleware function but got a ' + gettype(fn))v

node.js - 管道未启动后nodejs流完成回调

node.js - 使用 Node sdk 将模块连接到 Edge Hub 时出错 - NotConnectedError : unable to get local issuer certificate

templates - NodeJS + Express + Handlebars - 找不到 View "index.html"

c# - ASP.NET:如何使用 aspnet_regsql.exe 创建登录系统?

jsp - 如何检查用户是否在 JSP 中具有特定角色?