Kay
Kay

Reputation: 19718

Node + Passport - How to implement JWT Role Based Auth on different routes?

i need to perform role based auth.

HOWEVER,

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.


1. /auth/token ( Generating a JWT Token)

   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);

2. passport.middleware.js

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) => {

            if (jwtPayload.idcheck === undefined) {
                console.log("no idcheck present");
                return done(null, false);
            }

            console.log("idcheck present", jwtPayload);
            return done(null, jwtPayload );
        }));
}

3. routes.js

 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);

Upvotes: 0

Views: 3409

Answers (1)

Peter Grainger
Peter Grainger

Reputation: 5137

The passport authentication middleware adds in your case the jwtPayload to your req.user property for use in the next middleware http://www.passportjs.org/docs/authenticate/

const checkDocsMiddleware = (req, res, next) =>  {
     if(req.user && !req.user.idCheck.document) {
       next(new Error('Document is false'))
     } else {
       next()
     }
}

this.router.post("/document", this.jwtGuard, checkDocsMiddleware, this.controller.document);

I would personally add a middleware per rule you wanted to add.

Upvotes: 1

Related Questions