Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distinguish between user types when authenticating with JWT

In my app (Mongo,Express,Node,React), I'm currently authenticating users from the client to the server using JSON Web tokens. However, I want to be able to have two different types of users access different halves of the app. What is the best way to go about this? I currently have both types of users saved in the same model with a boolean that differentiates them. To clarify, different types of users would be able to access different API's as well as different portions of the client side app.

Is there a package that handles this? JWT feature?

like image 670
Patrick Connors Avatar asked Jul 19 '17 21:07

Patrick Connors


1 Answers

There are 2 ways that you may do this:

  1. When you are encoding the JWT token, encode the user role also.
  2. When you decode the JWT token and get the user's ID, for example, query your data store to get that user's role.

Most of the packages will allow you to define what you want to encode.

Tips:

  1. Always set an expiry on your tokens. It's simply a date stored on the JWT. When you decode the token just make sure that the date is in future, if not deny access.

  2. Create a middleware that checks the user's role. For example:

router.get('/restricted-area', requiresAdmin, (req, res, next) => {
  // only admin can access this
});

function requiresAdmin(req, res, next) {
  if(req.user.admin !== true) {
     res.status(401).end();
  } else {
     next();
  }
}
like image 77
Lucky Soni Avatar answered Oct 11 '22 10:10

Lucky Soni