我目前在使用PassportJS在我的SailsJS应用中验证用户时遇到问题。
我根据this tutorial使用sails-generate-auth生成了身份验证所需的所有内容。
似乎POST请求的路由正确,如routes.js文件中所定义:
'post /auth/local': 'AuthController.callback',
'post /auth/local/:action': 'AuthController.callback',
在AuthController中,我有以下代码:
callback: function (req, res) {
function tryAgain (err) {
// Only certain error messages are returned via req.flash('error', someError)
// because we shouldn't expose internal authorization errors to the user.
// We do return a generic error and the original request body.
var flashError = req.flash('error')[0];
if (err && !flashError ) {
req.flash('error', 'Error.Passport.Generic');
} else if (flashError) {
req.flash('error', flashError);
}
req.flash('form', req.body);
// If an error was thrown, redirect the user to the
// login, register or disconnect action initiator view.
// These views should take care of rendering the error messages.
var action = req.param('action');
switch (action) {
case 'register':
res.redirect('/register');
break;
case 'disconnect':
res.redirect('back');
break;
default:
res.redirect('/login');
}
}
passport.callback(req, res, function (err, user, challenges, statuses) {
if (err || !user) {
return tryAgain(challenges);
}
req.login(user, function (err) {
if (err) {
return tryAgain(err);
}
// Mark the session as authenticated to work with default Sails sessionAuth.js policy
req.session.authenticated = true
// Upon successful login, send the user to the homepage were req.user
// will be available.
res.redirect('/user/show/' + user.id);
});
});
},
我在Jade模板中提交登录表单:
form(role='form', action='/auth/local', method='post')
h2.form-signin-heading Please sign in
.form-group
label(for='username') Username
input.form-control(name='username', id='username', type='username', placeholder='Username', required='', autofocus='')
.form-group
label(for='password') Password
input.form-control(name='password', id='password', type='password', placeholder='Password', required='')
.form-group
button.btn.btn-lg.btn-primary.btn-block(type='submit') Sign in
input(type='hidden', name='_csrf', value='#{_csrf}')
我检查了传递给为password.callback(..)调用指定的回调函数的值:
passport.callback(req, res, function (err, user, challenges, statuses) {
用户变量设置为" false"。我想,这是错误的来源。
有趣的是,当用户注册后调用callback()函数时, user 变量被设置为包含用户名,电子邮件等所有值的用户对象。
如果您想查看其他源文件,我的项目可以在this repository的github上找到。
感谢任何帮助。
希蒙
答案 0 :(得分:2)
您使用model["comment"]
作为identifier
usernameField
(即默认设置)并在登录视图中使用LocalStrategy
,这意味着身份验证框架不会收到用户名并触发username
错误。
将登录视图中的字段名称更改为Missing Credentials
或通过护照配置文件(identifier
)设置相应的usernameField
:
config/passport.js