congtrungvnit
congtrungvnit

Reputation: 665

Role based authorization with express-jwt?

I am using express-jwt to protect my API endpoint so that only authenticated users can access my APIs. Now I want to also protect my APIs based on user's role too. For example, user can only access some APIs if they are admin, some others if they are super admin, etc. How can I achieve this? I found in express-jwt github doc this code snippet:

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 doing authorization in API controller function. Is it the only and recommended way? Are there any better ways to do this? Any advices about best practices for this?

Upvotes: 8

Views: 7839

Answers (1)

Derick Bailey
Derick Bailey

Reputation: 72868

Is it the only and recommended way?

pretty much, yeah.

this isn't a "controller function", though. this is an example of middleware, which is what 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's 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 variations on this setup that can be used, but this gets the idea across.

Upvotes: 10

Related Questions