简体   繁体   English

基于角色的jwt授权

[英]Role based jwt authorization

I am trying to authenticate a Node.js API with JSON Web Tokens. 我正在尝试使用JSON Web令牌验证Node.js API。 I could generate the token authenticate the users. 我可以生成令牌来验证用户。 Now I need to proptect my API based on the user roles. 现在我需要根据用户角色来检测我的API。 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);

This way, I protect the API say /api/check . 这样,我保护API说/api/check This can be accessed by admin user only. 这只能由admin user访问。 Now I have another super user who can access /api/validate which the admin user can't access. 现在我有另一个super user可以访问/api/validate admin user无法访问的内容。 How can I protect /api/validate only for super user . 我如何只为super user保护/api/validate 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;
     }  
};

Similarly requireSuperUser function for super user check.Is this the right way to do admin/super user check? 同样requireSuperUser函数用于超级用户检查。这是正确的方式进行管理员/超级用户检查吗?

When creating the JWT, you can provide your own payload as a private claim. 创建JWT时,您可以将自己的有效负载作为私有声明提供。 Eg: 例如:

{
  "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"
  ]
}

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. 然后需要解码令牌(最好使用express.js中间件用于此身份验证/授权目的)并检查角色并在不允许时抛出HTTP 401。 When it's allowed, call next(); 当它被允许时,调用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);

For more information on JWT claims: https://jwt.io/introduction 有关JWT声明的更多信息: https//jwt.io/introduction

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

Added requireAdmin function and checked if the role is admin by decoding the payload. 添加了requireAdmin函数,并通过解码有效负载来检查角色是否为admin。

api.post('/create',requireAdmin, function (req, res) {
   //.....
}

function requireAdmin(request, response, next) {
    if (request.decoded.role != 'admin') {
        response.json({message: 'Permission denied.' });
    }
    else {
        next();
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM