您好我正在尝试使用护照本地策略实施登录。由于一些奇怪的原因,当我从邮递员发送请求时,我的代码可以工作,但是当我从我的角度项目中调用相同的动作时,它不起作用。追查问题我想出了:
当我从邮递员发送请求时,会话看起来像这样:
Session {
cookie: {
path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true
},
passport: {
user: 58f0865eb9b69e1d38fa135b
}
}
当我从角度发送请求时,会话看起来像这样:
Session {
cookie: {
path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true
}
}
因为护照策略无法反序列化用户。我不知道为什么会这样,任何帮助都将受到高度赞赏。
服务器代码:
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator({
customValidators: {
isArray: function (value) {
return Array.isArray(value);
}
},
errorFormatter: function (param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while (namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg: msg,
value: value
};
}
}));
app.use(cookieParser());
app.use(expressSession({ secret: 'untoldstoryofninja', resave: false, saveUninitialized: true }));
app.use(cors());
app.use(passport.initialize());
app.use(passport.session());
// routes ========================================================================================
app.use(require('./config/routes/routes.js')(passport));
app.all('*', (req, res) => res.status(404).send({ msg: 'No API Route.' }));
护照策略:
module.exports = function (passport) {
passport.use(new LocalStrategy({ usernameField: "username", passwordField: "password" },
function (username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (user.comparePassword(password, function (err, isMatch) {
if (isMatch && !err) {
done(null, user)
} else {
done(null, false);
}
}));
});
}
));
passport.serializeUser(function (user, done) {
done(null, user._id);
});
passport.deserializeUser(function (id, done) {
User.findById({ _id: id }, function (err, user) {
done(err, user);
});
});
};
答案 0 :(得分:0)
你需要做
passReqToCallback:true
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'passwd',
passReqToCallback: true,
session: false
},
function(req, username, password, done) {
// request object is now first argument
// ...
}
));
还要确保您的字段名称与
匹配sernameField:' email',
passwordField:' passwd',