我试图在我的网站上对用户进行身份验证,但我收到了此错误
未知身份验证策略' local-login'
我已经尝试更改策略的名称,我也读过SO中的其他帖子,但没有找到解决方案。
// Passport
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
connection.query('SELECT * FROM `users` WHERE `id` = ' + connection.escape(id), function(err, rows) {
done(err, rows[0]);
});
});
passport.use('local-login', new LocalStrategy({
usernameField : 'username',
passwordField : 'password'
},
function(req, username, password, done) {
connection.query('SELECT * FROM `users` WHERE `username` = ' + connection.escape(username), function(err, rows) {
if(err)
return done(err);
if(!rows.length) {
return done(null, false, req.flash('loginMessage', 'Invalid username or password. Please try again.'));
}
if(!(rows[0].password == password))
return done(null, false, req.flash('loginMessage', 'Invalid username or password. Please try again.'));
return done(null, rows[0]);
});
}));
}
// Express Router
app.use(sessionMiddleware);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use('/static', express.static('./static'));
app.post('/login/auth', passport.authenticate('local-login', {
successRedirect: '/dashboard',
failureRedirect: '/',
failureFlash: true
}));
答案 0 :(得分:2)
首先检查您的安装:
npm install passport passport-local --save
然后导入护照如下:
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
在app.use()
方法之前:
...
..
app.use(passport.initialize());
app.use(passport.session());
然后按如下方式使用它。 (无需将'local-login'作为第一个参数)
passport.use(new LocalStrategy({
usernameField : 'username',
passwordField : 'password'
}, (req, username, password, done) => {
// Your logic here...
...
..
}));
}
最后在您的路由器中:
app.post('/login/auth', passport.authenticate('local', {
successRedirect: '/dashboard',
failureRedirect: '/',
failureFlash: true }),
function(req, res) {
res.redirect('/');
});
更多信息: passport-local