基于角色的jwt授权 [英] Role based jwt authorization

查看:143
本文介绍了基于角色的jwt授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JSON Web令牌对Node.js API进行身份验证.我可以生成令牌来对用户进行身份验证.现在,我需要根据用户角色保护我的API. 这是我路由中间件以进行身份​​验证和检查令牌的方法.

I am trying to authenticate a Node.js API with JSON Web Tokens. I could generate the token authenticate the users. Now I need to proptect my API based on the user roles. Here is how I route middleware to authenticate and check token.

var app = express();

var apiRoutes = express.Router();
apiRoutes.use(function (req, res, next) {

    var token = req.body.token || req.param('token') || req.headers['x-access-token'];

    if (token) {
        jwt.verify(token, app.get('superSecret'), function (err, decoded) {
            if (err) {
                return res.json({ success: false, message: 'Failed to authenticate token.' });
            } else {
                req.decoded = decoded;
                next();
            }
        });

    } else {
        return res.status(403).send({
            success: false,
            message: 'No token provided.'
        });
    }
});

apiRoutes.get('/check', function (req, res) {
    //...
});

app.use('/api', apiRoutes);

这样,我保护API说/api/check.只能由admin user访问.现在,我有另一个super user可以访问admin user无法访问的/api/validate.如何仅为super user保护/api/validate.我需要再编写一个中间件来做到这一点吗?

This way, I protect the API say /api/check. This can be accessed by admin user only. Now I have another super user who can access /api/validate which the admin user can't access. How can I protect /api/validate only for super user. Do I need to write one more middleware to do this?

这是我现在进行管理员检查的方式,

Here is how I do the admin check now,

apiRoutes.post('/delete/:id',requireAdmin, function (req, res) {
//do the rest
};

function requireAdmin(req, res, next) {
    var currentUserRole=".."; //get current user role
    if('admin' == currentUserRole )
     {
         next();
     }
     else{
          next(new Error("Permission denied."));
    return;
     }  
};

类似requireSuperUser的超级用户检查功能.这是执行管理员/超级用户检查的正确方法吗?

Similarly requireSuperUser function for super user check.Is this the right way to do admin/super user check?

推荐答案

创建JWT时,您可以提供自己的有效负载作为私有声明.例如:

When creating the JWT, you can provide your own payload as a private claim. E.g.:

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true,
  "superUser": false
}

以同样的方式,您可以列出已登录用户的一组用户角色

Same way you can perhaps list a set of user roles for the logged in user

{
  "sub": "1234567890",
  "name": "John Doe",
  "roles": [
    "ADMIN",
    "SUPERUSER"
  ]
}

然后需要的是解码令牌(为此认证/授权目的最好使用express.js中间件)并检查角色,并在不允许的情况下抛出HTTP 401.如果允许,请致电next();继续并输入匹配的路线.

What is required then is to decode the token (best use express.js middleware for this authentication/authorization purpose) and check the roles and throw a HTTP 401 when it's not allowed. When it's allowed, call next(); to go ahead and enter the matching route.

这种可能的中间件功能的小例子:

Small example of such a possible middleware function:

function canAccess(req, res, next) {
  checkAuthorization(req, function (err, authorized) {
      if (err || !authorized) {
          res.send({message: 'Unauthorized', status: 401});
      }

      next();
  });

  function checkAuthorization(req, callback) {
      // jwt decode and actual authentication admin/superuser matching goes here..
  }
}

router.use(canAccess);

有关JWT索赔的更多信息: https://jwt.io/introduction

For more information on JWT claims: https://jwt.io/introduction

有关expressjs中间件的更多信息: https://expressjs.com/en/guide /using-middleware.html

For more information on expressjs middleware: https://expressjs.com/en/guide/using-middleware.html

这篇关于基于角色的jwt授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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