gpt4 book ai didi

javascript - 未知的身份验证策略 "local"

转载 作者:行者123 更新时间:2023-11-30 09:28:18 26 4
gpt4 key购买 nike

我正在尝试对我网站上的用户进行身份验证,但出现此错误

Unknown authentication strategy '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
}));

最佳答案

首先检查你的安装:

npm install passport passport-local --save

然后像下面这样导入 Passport :

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

关于javascript - 未知的身份验证策略 "local",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48006327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com