【问题标题】:Can I use passport-jwt conditionally?我可以有条件地使用passport-jwt吗?
【发布时间】:2018-09-27 02:28:20
【问题描述】:

意思是,在我的应用程序中,我想检查客户端请求中是否存在 customId。如果是,我将使用我的自定义逻辑进行身份验证。 如果 customId 不存在,我想使用 passport-jwt 身份验证。

passport 在服务器启动时注册它的初始化方法。 我的具体问题是如何仅在 customId 不存在时使用 passport.authenticate。

非常感谢任何帮助。

【问题讨论】:

    标签: express passport-jwt


    【解决方案1】:

    是的,你可以,这只是中间件!这是您将如何做的示例,我没有运行此代码,因此它可能无法构建,但它显示了如何做您所追求的。

    const express = require('express');
    const passport = require('passport');
    const passportJWT = require('passport-jwt');
    
    // My express application where I setup routers, middleware etc
    const app = express();
    
    // Initialise passport
    app.use(passport.initialize());
    
    // Setup my passport JWT strategy, this just setups the strategy it doesn't mount any middleware
    passport.use(new passportJWT.Strategy({
        secretOrKey: '',
        issuer: '',
        audience: '',
    }, (req, payload, done) => {
        doSomeFancyAuthThingy(payload, (err, user) => {
            done(err, user);
        });
    }));
    
    // Now create some middleware for the authentication
    app.use((req, res, next) => {
        // Look to see if the request body has a customerId, in reality
        // you probably want to check this on some sort of cookie or something
        if (req.body.customerId) {
            // We have a customerId so just let them through!
            next();
        } else {
            // No customerId so lets run the passport JWT strategy
            passport.authenticate('jwt', (err, user, info) => {
                if (err) {
                    // The JWT failed to validate for some reason
                    return next(err);
                }
    
                // The JWT strategy validated just fine and returned a user, set that
                // on req.user and let the user through!
                req.user = user;
                next();
            });
        }
    });
    

    如您所见,您要寻找的主要内容是我们创建中间件的位置。这里我们只是创建自己的中间件并运行检查(if 语句),如果失败则运行 passport.authenticate,它会触发我们在 passport.use 块上创建的策略。

    这将允许您有条件地使用 Passport 进行任何类型的身份验证!

    【讨论】:

    • 太棒了!是的,这就是我要找的。我将这个新的中间件保存在一个单独的文件中,这增加了混乱。我想,我可以在做护照之后导出护照。使用....并在另一个文件中要求它,我保留了中间件并在那里使用护照。身份验证对吗?抱歉,如果您觉得这很愚蠢,我刚开始使用 express :)
    • 如果您的中间件在另一个文件中,您可以简单地要求在该文件中带有require('passport'); 的护照中调用passport.authenticate。不需要注入它,它是一种单例。完全不用担心!护照是一头难管理的丑陋野兽。
    • 哈哈!非常感谢您的回复:)
    • 别担心,希望这能为您解决问题,祝您学习顺利:)
    猜你喜欢
    • 2017-12-18
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    相关资源
    最近更新 更多