Role based jwt authorization

2019-03-28 13:05发布

问题:

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

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

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

回答1:

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

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

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

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



回答2:

Added requireAdmin function and checked if the role is admin by decoding the payload.

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

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


标签: node.js jwt