策略实施与
passport.authenticate验证请求和处理成功/失败一起使用。
假设您正在使用此路由(向其传递了电子邮件地址和密码):
app.post('/login', passport.authenticate('local', { successRedirect: '/loggedin', failureRedirect: '/login', // see text failureFlash: true // optional, see text as well});这将调用该策略中的代码,其中可能发生以下三种情况之一:
- 尝试获取用户信息时发生内部错误(例如数据库连接已断开);这个错误将转嫁:
next(err)
; 这将由Express处理并生成HTTP 500响应; - 提供的凭据无效(没有用户使用提供的电子邮件地址,或者密码不匹配);在这种情况下,你不产生一个错误,但你传递一个
false
为用户对象:next(null, false)
; 这将触发failureRedirect
(如果您未定义,则会生成HTTP 401未经授权的响应); - 一切检查出来,你有一个有效的用户对象,所以你把它传递:
next(null, user)
; 这将触发successRedirect
;
如果验证无效(但不是内部错误),则可以在回调中传递额外的消息:
next(null, false, { message : 'invalid e-mail address or password' });如果您已经使用
failureFlash并 安装了connect-
flash中间件,则所提供的消息将存储在会话中,并且可以方便地访问,例如在模板中使用。
编辑: 也可以自己完全处理身份验证过程的结果(而不是Passport发送重定向或401):
app.post('/login', function(req, res, next) { passport.authenticate('local', function(err, user, info) { if (err) { return next(err); // will generate a 500 error } // Generate a JSON response reflecting authentication status if (! user) { return res.send({ success : false, message : 'authentication failed' }); } // *********************************************************************** // "Note that when using a custom callback, it becomes the application's // responsibility to establish a session (by calling req.login()) and send // a response." // Source: http://passportjs.org/docs // *********************************************************************** req.login(user, loginErr => { if (loginErr) { return next(loginErr); } return res.send({ success : true, message : 'authentication succeeded' }); }); })(req, res, next);});


