Saurabh Verma
Saurabh Verma

Reputation: 129

How to implement role based authorization in Node.js using token based authentication?

How can I implement multiple authentications in nodejs for a education firm, having three role- student, parent, and admin using REST API approach i.e token based authentication.

Upvotes: 1

Views: 2189

Answers (1)

Kay
Kay

Reputation: 19660

0. Concept

A JWT token (https://jwt.io/), contains a payload, within this payload you can specify a custom role object. Within the role object you can set boolean values to determine if the role is student, parent or admin.

Example Payload

{
  ...
  "role": {
     student: true,
     parent: false,
     admin: false,
  }
}

When you go to generate your token for a specific user, attach the payload details to the token. (Ofcourse you would adjust the payload details depending on whether you want the user to be a student, parent or admin).

Whenever a user makes a request in the future using their token, you can make a callback to check their token and look at the payload.role object to see what role the user has and then make a decision as to whether they are authorized to perform a specific action or not.

1. Generating the token

See https://www.npmjs.com/package/jsonwebtoken for more information on generating a token.

   const payload = {
     userid: 123,
     role: {
       student: false,
       parent: false,
       admin: true,
     },
   };

   const signOptions = {
     issuer: this.config.jwt.issuer,
     subject: payload.userid,
     audience: this.config.jwt.audience,
     expiresIn: "730d",
     algorithm: "RS256",
   };

   const token = jwt.sign(payload, this.config.jwt.privateKey.replace(/\\n/g, "\n"), signOptions);

2. Middleware To Check Role

You should already have something like this if youre are using passport with JWT authentication.

const authGuard = PassportMiddleware.authenticate("jwt", { session: false });

router.get("/admin", authGuard, controller.index);

We need a new middleware to handle the checking of roles. We will call this middleware adminGuard. After authenticating using the authGuard middleware the req object will contain a user (which is the jwt payload). Now that we have the user information we can check what role they have.

const adminGuard = (req, res, next) =>  {
     if(req.user && !req.user.role.admin) {
       next(new Error('You are not an admin'));
     } else {
       next();
     }
}

router.get("/admin", authGuard, adminGuard, controller.index);

You can create a new middleware guard for each role.

Upvotes: 3

Related Questions