简体   繁体   中英

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

如何使用 REST API 方法(即基于令牌的身份验证)在具有三个角色 - 学生、家长和管理员的教育公司的 nodejs 中实现多个身份验证。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM