Role-based authorization with exress-jwt?

I use express-jwt to protect the API endpoint so that only authenticated users can access my APIs. Now I also want to protect my APIs based on the user role. For example, a user can only access certain APIs if they are an administrator, some others if they are a super-administrator, etc. How can i achieve this? I found this snippet in express jwt github doc:

app.get('/protected',
  jwt({secret: 'shhhhhhared-secret'}),
  function(req, res) {
    if (!req.user.admin) return res.sendStatus(401);
    res.sendStatus(200);
  });

It looks like this code is performing authorization on an API controller function. Is this the only and recommended way? Are there any better ways to do this? Any tips on best practices for this?

+4
source share
1 answer

Is this the only and recommended way?

To a large extent, yes.

this is not a “controller function”. This is an example of middleware that you want to use in this case.

a more complete example would be:


var router = new express.Router();

// process jwt stuff
var processjwt = jwt({secret: 'shhhhhhared-secret'});

// authorization check
function authorizationCheck(req, res, next) {
  if (!req.user.admin) { 
   return res.sendStatus(401);
  } else {
    // move to the next middleware, cause it ok
    next();
  } 
}

// the real route handler
function myRouteHandler(req, res){
  doSomeWork(function(err, data){
    if (err) { return next(err); }
    res.json(data);
  });
}

// put it all together
router.use("/protected", processjwt, authorizationCheck);
router.get("/protected", myRouteHandler);

There are dozens of options for this setup that you can use, but it gives an idea.

+5
source

All Articles