[英]passportjs authentication failed
I'm trying to authenticate users using passportjs for the first time but I've been having trouble getting it to work. 我正在尝试首次使用passportjs对用户进行身份验证,但一直无法正常工作。 So this is the relevant code I'm working with
这是我正在使用的相关代码
Index.js route file Index.js路由文件
var express = require('express');
var router = express.Router();
var passport = require('passport');
var bcrypt = require('bcryptjs');
router.post('/', passport.authenticate('local', {
successRedirect: 'home',
failureRedirect: '/'
}));
app.js app.js
// Authentication packages
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var MySQLStore = require('express-mysql-session')(session);
var bcrypt = require('bcryptjs');
passport.use(new LocalStrategy(function(email, password, done) {
console.log(email);
console.log(password);
res.locals.connection.query('SELECT id, password FROM users WHERE email = ?', [email], function(err, user) {
console.log(user);
if (err) {return done(err)};
if (user.length === 0) {
done(null, false);
};
const hash = user[0].password.toString();
console.log(hash);
bcrypt.compare(password, hash, function(err, res) {
if (res === true) {
return done(null, {user_id: user[0].id});
} else {
return done(null, false);
}
});
});
}
));
When i input a valid email address and password, I don't get redirected to the home like i want. 当我输入有效的电子邮件地址和密码时,我不会像我想要的那样被重定向到家庭。 Instead I'm redirected back to the login page.
相反,我被重定向回登录页面。 Same thing happens when i use an invalid email address.
当我使用无效的电子邮件地址时,也会发生同样的事情。 I also don't see the email and password even though I'm trying to console log it when i submit the login form.
即使我在尝试提交登录表单时尝试控制台登录,也看不到电子邮件和密码。
Can anyone help me out here please. 任何人都可以在这里帮助我。
I noticed you have email
as the username. 我注意到您使用
email
作为用户名。 I had a similar problem and found that the solution was just to add usernameField
to the strategy options: 我遇到了类似的问题,发现解决方案只是将
usernameField
添加到策略选项中:
new LocalStrategy({usernameField: 'email'}, function(email, password, done){...})
I think you may either need to place your passport.use
in your route index.js file, or somehow pass the passport
instance created in app.js as a parameter to index.js 我想你可能要么需要把你的
passport.use
在index.js文件的路径,或以某种方式通过passport
在app.js创建的实例作为参数传递给index.js
Could you try that? 你能尝试一下吗? It's possible that a new instance is created everytime you do require('passport')
每次您需要时都可能创建一个新实例(“ passport”)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.