仅将护照身份验证添加到特定路线组

时间:2019-03-01 11:32:35

标签: node.js express passport.js

我如何制定以下策略?

我想将jwt auth策略添加到/api/v1/apiKeys下的所有端点。

passport.use('jwtStrategy', new JwtStrategy({ passReqToCallback: true, jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: process.env.APP_SECRET },
            (req: Request, payload, done) => {
                console.log('here');
                const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

                if (ip !== payload.ip) {
                    done(new Error("Invalid token"), false);
                } else {
                    req.headers["clientId"] = payload.clientId;
                    done(null, true);
                }
            }));

        router.use("/api/v1/apiKeys", passport.authenticate('jwtStrategy', { session: false }));

        router.post("/api/v1/apiKeys/generateApiKey",  async (req, res) => {
            const keyConfig = req.body;
            const { clientId } = <any>req.headers;
            const result = await ApiKeysServiceInstance.buildApiKey(clientId, keyConfig);
            res.json(result);
        });

使用当前配置,尝试时我总是收到401响应 张贴在/api/v1/apiKeys/generateApiKey

如果我在级别上添加passport.authenticate方法,它将起作用。像这样:

router.post("/api/v1/apiKeys/generateApiKey",  passport.authenticate('jwtStrategy', { session: false })), async (req, res) => {
    const keyConfig = req.body;
    const { clientId } = <any>req.headers;
    const result = await ApiKeysServiceInstance.buildApiKey(clientId, keyConfig);
    res.json(result);
});

感谢您的帮助。

0 个答案:

没有答案