我目前在使用 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 变量被正确设置为包含所有值(如用户名、电子邮件等)的用户对象。
如果您想检查其他源文件,我的项目在 github 上可用 this repository .
感谢任何帮助。
西蒙
最佳答案
您正在使用 identifier
作为 LocalStrategy
的 usernameField
(即默认设置)并且有 username
在登录 View 中,这意味着身份验证框架没有接收到用户名并触发 Missing Credentials
错误。
要么将登录 View 中的字段名称更改为identifier
,要么通过护照配置文件(config/passport.js
)设置适当的usernameField
>):
local: {
strategy: require('passport-local').Strategy,
options: {
usernameField: 'username'
}
}
关于javascript - SailsJS + PassportJS (sails-generate-auth) - 无法登录用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33201610/