所以我正在使用 isomorphic-redux 和 React.js 构建一个 Web 应用程序。我目前正在尝试使用 Node.js 中的护照进行基本身份验证。但是我遇到了一个问题,当我尝试登录时,我的 cookie 会话似乎没有加载到浏览器中。
这是迄今为止我编写的代码的精简版本。
服务器.js
import Express from 'express';
import passport from 'passport';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import expressSession from 'express-session';
import serverConfig from './config';
const app = new Express();
// Apply body Parser and server public assets and routes
app.use(cookieParser());
app.use(bodyParser.json({ limit: '20mb' }));
app.use(bodyParser.urlencoded({ limit: '20mb', extended: true }));
app.use(expressSession({
secret: serverConfig.sessionSecret,
resave: false,
saveUninitialized: false
}));
import pp from './passport';
pp();
app.use(passport.initialize());
app.use(passport.session());
护照.js
import passport from 'passport';
import mongoose from 'mongoose';
import path from 'path';
import User from './models/user.model';
import local from './strategies/local';
const pp = () => {
// Serialize sessions
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// Deserialize sessions
passport.deserializeUser(function(id, done) {
User.findOne({
_id: id
}, '-salt -password', function(err, user) {
done(err, user);
});
});
local();
}
export default pp;
./strategies/local.js
import passport from 'passport';
import passportLocal from 'passport-local';
import mongoose from 'mongoose';
const LocalStrategy = passportLocal.Strategy;
const User = mongoose.model('User');
const local = () => {
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
},
(username, password, done) => {
User.findOne({ username: username }, (err, user) => {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, {
message: 'Unknown user or invalid password'
});
}
if (!user.authenticate(password)){
return done(null, false, {
message: 'Unknown user or invalid password'
});
}
return done(null, user);
});
}
));
}
export default local;
当我登录时,它能够序列化会话,但是由于我猜,会话不会被存储,它不会反序列化会话。