【问题标题】:Passport auth stuck in controller?护照验证卡在控制器中?
【发布时间】:2018-04-16 12:55:12
【问题描述】:

我尝试将我的路由转发到控制器,但它似乎不适用于 Passport.js

router.get('/login', (req, res, next) => UserController.getLogin(req, res, next));
router.post('/login', (req, res, next) => UserController.postLogin(req, res, next));

现在,唯一不起作用的路线是使用 Passport 的路线。

static getLogin(req: Request, res: Response, next: NextFunction) {
...
}
static postLogin(req: Request, res: Response, next: NextFunction) {

        passport.authenticate('local', {
            successRedirect: '/success',
            failureRedirect: '/failed'
        });
        // res.send('hello from POST'); would work
}

我正在使用 TypeScript

【问题讨论】:

    标签: javascript node.js typescript passport.js


    【解决方案1】:

    Passport 是异步的。它通常用作传递回调的中间件。例如,文档有这个例子:

    app.post('/login', passport.authenticate('local', { successRedirect: '/',
                                                    failureRedirect: '/login' }));
    

    这里要记住的是passport.authenticate 返回一个接受(req, res, next) 的函数。然后它作用于该数据并在完成后调用next。在您的代码中,您正在调用authenticate(返回一个函数),然后什么也不做。我有一些建议。

    首先是通过简化事物来减少噪音。根据框架,您通常可以传递一堆函数来处理路由。在这种情况下,您只需要一个。

    router.post('/login', passport.authenticate('local', {
        successRedirect: '/success',
        failureRedirect: '/failed'
    }))
    

    如果您想做的不仅仅是身份验证,您可以传递更多功能。

    router.post('/login', 
        passport.authenticate('local', {
            successRedirect: '/success',
            failureRedirect: '/failed'
        }),
        UserController.doThing // accepts (req, res, next)
    )
    

    您会注意到我没有创建一个匿名函数来将相同的 3 个参数传递给控制器​​。这不是必需的。在大多数情况下,它们是相同的。

    【讨论】:

    • 我试着模仿一下[link]github.com/Microsoft/TypeScript-Node-Starter/blob/master/src/…,像这样使用app.post("/login", userController.postLogin);的控制器,这样结构会更有条理。这不是正确的方法吗?
    • 您可以遵循该模式。如果是这样,您希望为authenticate 添加最终执行并传入参数req, res, next... failureRedirect: '/failed'})(req,res,next)
    • 谢谢!我实际上忘了自调用函数passport.authenticate('local', {...})(req, res, next); 工作得很好
    猜你喜欢
    • 2018-10-14
    • 2015-01-19
    • 2020-11-12
    • 1970-01-01
    • 2018-10-26
    • 2016-01-19
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多