我已经研究了如何通过this question 在节点中进行错误处理,但我不确定passport在身份验证失败时会做什么。我有以下LocalStrategy:
passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' },
function(email, password, next) {
User.find({email: UemOrUnm}, function(err, user){
if (err) { console.log('Error > some err'); return next(err); }
if (!user) { console.log('Error > no user'); return next('Incorrect login or password'); }
if (password != user.password) {
return next(Incorrect login or password);
}
return next(null, user);
});
}
));
在我看到'Error > some err‘控制台打印输出后,没有发生任何其他事情。我认为它应该使用错误参数继续下一条路径,但它似乎没有做到这一点。到底怎么回事?
发布于 2013-03-30 05:13:37
该策略实现与passport.authenticate
结合使用,既可以对请求进行身份验证,也可以处理成功/失败。
假设您正在使用此路由(向其传递一个电子邮件地址和密码):
app.post('/login', passport.authenticate('local', {
successRedirect: '/loggedin',
failureRedirect: '/login', // see text
failureFlash: true // optional, see text as well
});
这将调用策略中的代码,其中可能出现以下三种情况之一:
next(err)
;这将由Express处理并生成HTTP500响应;false
作为user对象传递:next(null, false)
;这将触发failureRedirect
(如果您没有定义,将生成HTTP401未授权响应);next(null, user)
;这将触发user如果身份验证无效(但不是内部错误),您可以在回调中传递额外的消息:
next(null, false, { message : 'invalid e-mail address or password' });
如果您使用了failureFlash
并安装了the connect-flash middleware,则提供的消息将存储在会话中,并且可以轻松访问,例如,在模板中使用。
编辑:也可以完全自己处理身份验证过程的结果(而不是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);
});
发布于 2015-05-13 04:00:37
克里斯蒂安所说的是你需要添加一个函数
req.login(user, function(err){
if(err){
return next(err);
}
return res.send({success:true});
});
因此,整个路线将是:
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(401,{ success : false, message : 'authentication failed' });
}
req.login(user, function(err){
if(err){
return next(err);
}
return res.send({ success : true, message : 'authentication succeeded' });
});
})(req, res, next);
});
发布于 2015-02-21 01:44:58
您需要添加req.logIn(function (err) { });
并在回调函数中执行成功重定向
https://stackoverflow.com/questions/15711127
复制相似问题