title: Node + Passport - How to implement JWT Role Based Auth on different routes?
body: <p>i need to perform role based auth. </p>
  
  <ul>
  <li><p>I am generating a JWT token with the payload that contains data about a specific customer. For example, if they are allowed to use the <code>document</code> &amp; <code>face</code> feature.</p></li>
  <li><p>I have created a passport.middleware which verifies the jwt token, fine.</p></li>
  <li><p>I am applying this jwt middleware to my routes, fine. </p></li>
  </ul>
  
  <p>HOWEVER, </p>
  
  <ul>
  <li>for the <code>/document</code> route i want to add a guard here to check if the jwt payload has <code>idcheck.document == true</code>. </li>
  <li>Similarly a user can only call the <code>/face</code>endpoint if <code>idcheck.face == true</code></li>
  </ul>
  
  <p>At the moment i am only checking if the jwt is valid. Each endpoint should be guarded to check the token is valid AND whether they have the role to access the endpoint. How can i extend my code to implement this, what is the best way here.</p>
  
  <hr>
  
  <p><strong>1. /auth/token</strong> ( Generating a JWT Token)</p>
  
  <pre><code>   const payload = {
          idcheck: {
              productId,
              document: true,
              face: false,
          },
      };
  
      const signOptions = {
          issuer:  this.config.jwt.issuer,
          subject:  productId,
          audience:  this.config.jwt.audience,
          expiresIn:  "730d",
          algorithm:  "RS256",
      };
  
      const token = jwt.sign(payload, this.config.jwt.privateKey.replace(/\\n/g, "\n"), signOptions);
  </code></pre>
  
  <p><strong>2. passport.middleware.js</strong></p>
  
  <pre><code>private jwtStrategy(): void {
  
          const verifyOptions: StrategyOptions = {
  
              jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
              secretOrKey: this.config.jwt.publicKey.replace(/\\n/g, "\n"),
              issuer:  this.config.jwt.issuer,
              audience:  this.config.jwt.audience,
              algorithms:  ["RS256"],
          };
  
          this.passport.use(new Strategy(verifyOptions, (jwtPayload, done) =&gt; {
  
              if (jwtPayload.idcheck === undefined) {
                  console.log("no idcheck present");
                  return done(null, false);
              }
  
              console.log("idcheck present", jwtPayload);
              return done(null, jwtPayload );
          }));
  }
  </code></pre>
  
  <p><strong>3. routes.js</strong></p>
  
  <pre><code> this.jwtGuard = PassportMiddleware.authenticate("jwt", { session: false });
  
   this.router.post("/document", this.jwtGuard, this.controller.document);
   this.router.post("/face", this.jwtGuard, this.controller.face);
  </code></pre>