如何将 JWT 身份验证与 ACL 混合使用

How to mix jwt authentication with ACLs

本文关键字:ACL 混合 身份验证 JWT      更新时间:2023-09-26

我已经能够使用JWT策略实现护照,并且效果很好。 我的受 jwt 保护的路由看起来像这样...

app.get('/thingThatRequiresLogin/:id', passport.authenticate('jwt', { session: false }), thingThatRequiresLogin.findById);

现在,我需要将某些内容的访问限制为仅属于某个角色的登录用户。 我希望我能这样表达:

app.get('/thingThatRequiresLogin/:id', MAGIC, thingThatRequiresLogin.findById);

哪里MAGIC = require logged-in users, but only those with role x or y

node_acl似乎是一个很好的解决方案,我在一定程度上理解它,但后来我在文档中发现了这一点......

我们可以像这样保护资源:

app.put('/blogs/:id', acl.middleware(), function(req, res, next){…}

中间件将保护由 req.url 命名的资源,选择 用户来自 req.session.userId 并检查 req.method的权限, 所以以上相当于这样:

如何将其与我的 JWT 策略混合使用? 我唯一的想法是放弃node_acl middleware,而是将 ACL 检查代码添加到我的 jwt 策略中。 但这就是我遇到麻烦的地方。 我的 jwt 函数如下所示:

passport.use(new JwtStrategy(jwtOptions, function(jwt_payload, done) {
    User.findOne({id: jwt_payload.sub}, function(err, user) {
        if (err) {
            return done(err, false);
        }
        if (user) {
            done(null, user);
        } else {
            done(null, false);
            // or you could create a new account
        }
    });
}));

根据node_acl的说法,我可以问这样的事情...

acl.isAllowed('jsmith', 'blogs', ['edit','view','delete'])

那么我可以(我应该吗?)改变我的 JwtStrategy 来表达类似的话......

    if (user && acl.isAllowed(user.username, 'blogs', ['edit','view','delete']) {
        // ...

如果是这样,此函数如何知道资源名称'blogs'和权限['edit' etc]? 这些在定义路线时是已知的,但我认为我在策略函数中需要它们。 我做错了吗? 有人可以告诉我正确的方法吗?

app.get('/thingThatRequiresLogin/:id', 
  [
     passport.authenticate('jwt', { session: false }), 
     acl.middleware( 1, getUserId )
  ], 
  thingThatRequiresLogin.findById);

从这个要点中获取线索:https://gist.github.com/danwit/e0a7c5ad57c9ce5659d2以及关于 NPM 的node_acl文档:https://www.npmjs.com/package/acl#middlewareacl.middleware 有三个可选参数:acl.middleware(numPathComponents, userId, permissions)

numPathComponents: 1//要选择事物需要登录路径

userId:getUserId/

/getUserId 是一个返回 userId 的函数

我希望这有帮助