我使用PassportJS和我的本地策略遇到了问题。我正在使用ExpressJS 4。
我的app.js(缩小,没有快速初始化):
format()
我的策略(var express = require('express'),
ejs = require('ejs'),
path = require('path'),
expressLayouts = require('express-ejs-layouts'),
session = require('express-session'),
compression = require('compression'),
_ = require('lodash'),
fs = require('fs-extra'),
colors = require('colors'),
passport = require('passport'),
flash = require('connect-flash'),
localStrategyMiddleware = require('./middlewares/localStrategy'),
logMiddleware = require('./middlewares/log'),
localsMiddleware = require('./middlewares/locals'),
securityMiddleware = require('./middlewares/security');
this.app.use(session({
secret : 'd4qs45sdq6',
// name : 'sessionId',
// proxy: true,
resave: true,
saveUninitialized: true
}));
this.app.use(flash());
this.app.use(function(request, response, next) {
response.locals.flash = {
info: request.flash('info'),
success: request.flash('success'),
warning: request.flash('warning'),
danger: request.flash('danger')
};
next();
});
this.app.use(passport.initialize());
this.app.use(passport.session());
this.app.post('/test', passport.authenticate('local', {
successRedirect: '/user/success',
failureRedirect: '/user/failure',
failureFlash: true,
successFlash: true
}), function(request, response) {
console.log('test');
});
):
./middlewares/localStrategy
问题:我没有记录,我每次都被重定向到var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
sequelize = require('../databases/Database').connexion,
UserModel = require('../app/models/UserModel')(sequelize);
passport.use(new LocalStrategy(
function(username, password, done) {
console.log('test');
UserModel.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
passport.serializeUser(function(user, done) {
console.log(user);
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
console.log(id);
UserModel.findById(id, function(err, user) {
done(err, user);
});
});
module.exports = passport;
。
修改1:
user/failure
答案 0 :(得分:1)
如果您没有收到日志,则会告诉您app.js文件无法访问./middlewares/localStrategy
尝试更改
localStrategyMiddleware = require('./middlewares/localStrategy')
简单地
require('./middlewares/localStrategy')
此外,您需要更改表单上的名称属性以匹配护照使用的名称属性,我认为默认值是用户名和密码,因此除非您想在localStrategy中指定替代项,否则应使用以下内容。
<input type="text" name="username" placeholder="username">
<input type="text" name="password" placeholder="password">