8

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?

Axifive
  • 1,159
  • 2
  • 19
  • 31
congtrungvnit
  • 635
  • 1
  • 10
  • 16

1 Answers1

10

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.

Derick Bailey
  • 72,004
  • 22
  • 206
  • 219
  • Can you please give me more details about how you often do the authorization? Particularly, for example, I have 3 user roles, super admin, admin and user and 10 API endpoints, for simplicity purpose, lets call them API 1, API 2,... API 10. What if I want to let just super admin and admin have access to API 1 -> API 3, just super admin and user have access to API 4 -> API 6, and the others are available to all authenticated users? The solution that I can think is to write 2 middleware handlers, the one for API 1 -> API 3 and the other for API 4 -> API 6. What is yours? – congtrungvnit Apr 01 '16 at 10:22
  • 1
    Does this imply role info is stored in the token? – Learner Dec 19 '16 at 11:29