我尝试使用express4 / passportjs设置一个简单的本地策略验证,但永远不会调用authenticate函数: 这是我的代码
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
app.use(compress());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
/* AUTHENTIFICATION */
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
passport.use(new LocalStrategy(
function(username, password, done) { //THIS FUNCTION IS NEVER CALLED
console.log("Local strategy");
}
));
app.post('/login', function(req, res) {
console.log("user : ", req.body.username);
console.log("password : ", req.body.password);
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login' })
});
/* !AUTHENTIFICATION */
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'bower_components')));
app.use(express.static(path.join(__dirname, 'controllers')));
app.use(express.static(path.join(__dirname, 'modules')));
app.use('/', routes);
app.use('/users', users);
当我在/ login中发送帖子请求时,我在日志中看到用户名和密码,但password.authentificate
方法没有做任何事情。
它应该调用LocalStrategy
函数和console.log('策略')但它没有。
有人知道如何修复它吗?
由于
答案 0 :(得分:2)
authenticate()'s function signature is standard Connect middleware
。
因此应传递req, res, next
的引用
因此您可以将其用作路由中间件
app.post('/login', passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login' }));
或
app.post('/login', function(req, res, next) {
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login' })(req, res, next);
});