【问题标题】:Node + Passport - How to implement JWT Role Based Auth on different routes?Node + Passport - 如何在不同的路由上实现基于 JWT 角色的身份验证?
【发布时间】: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


【解决方案1】:

护照身份验证中间件在您的情况下将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);

我会亲自为您要添加的每个规则添加一个中间件。

【讨论】:

    猜你喜欢
    • 2020-07-29
    • 2016-05-01
    • 2018-08-28
    • 2016-11-04
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    相关资源
    最近更新 更多