【发布时间】:2019-03-30 01:34:40
【问题描述】:
我需要执行基于角色的身份验证。
我正在生成一个 JWT 令牌,其有效负载包含有关特定客户的数据。例如,如果他们被允许使用
document&face功能。我创建了一个验证 jwt 令牌的 passport.middleware,很好。
我正在将此 jwt 中间件应用到我的路由中,很好。
然而,
- 对于
/document路由,我想在此处添加一个保护来检查jwt 有效负载是否具有idcheck.document == true。 - 同样,如果
idcheck.face == true,用户只能调用/faceendpoint
目前我只检查 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。 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.路线.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);
【问题讨论】:
-
请不要被打字稿吓到,我会接受用js写的答案。
标签: node.js express jwt passport.js