节点 + 护照 - 如何在不同路由上实现基于 JWT 角色的身份验证?



我需要执行基于角色的身份验证。

  • 我正在生成一个 JWT 令牌,其中包含有关特定客户的数据的有效负载。例如,是否允许他们使用document&face功能。

  • 我创建了一个 passport.middleware 来验证 jwt 令牌,很好。

  • 我正在将此 jwt 中间件应用于我的路由,很好。

然而

  • 对于/document路线,我想在此处添加一个警卫以检查 JWT 有效负载是否idcheck.document == true.
  • 同样,用户只能在以下情况下调用/face终结点idcheck.face == true

目前,我只检查 jwt 是否有效。应保护每个终结点,以检查令牌是否有效,以及它们是否具有访问终结点的角色。我如何扩展我的代码来实现这一点,这里最好的方法是什么。


1./auth/token(生成 JWT 令牌(

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.护照中间件.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. 路线.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);

护照身份验证中间件会在您的案例中将jwtPayload添加到您的req.user属性中,以便在下一个中间件中使用 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);

我个人会根据您要添加的规则添加一个中间件。

最新更新