Reputation: 19718
i need to perform role based auth.
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 document
& face
feature.
I have created a passport.middleware which verifies the jwt token, fine.
I am applying this jwt middleware to my routes, fine.
HOWEVER,
/document
route i want to add a guard here to check if the jwt payload has idcheck.document == true
. /face
endpoint if idcheck.face == true
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
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