Express会话不存储会话

时间:2016-03-20 10:04:09

标签: express reactjs session-cookies passport.js express-session

所以我正在使用isomorphic-redux和React.js构建一个Web应用程序。我目前正在尝试使用Node.js中的护照进行基本身份验证。但是我遇到了一个问题,当我尝试登录时,我的cookie会话似乎没有在浏览器中加载。

这是我目前编写的代码的简化版本。

Server.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());

passport.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;

./策略/ 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;

当我登录时,它能够序列化会话,但是由于我猜测,会话没有被存储,它不会反序列化会话。

1 个答案:

答案 0 :(得分:0)

如果您希望会话是持久的,则需要告诉express-session模块存储它们的位置。首先,您需要建立一个商店:

var MongoStore = require('connect-mongo')(expressSession);
var oneHour = 3600;
var sessionStore = new MongoStore({
    url: 'mongodb://localhost:27017/my-session-store',
    touchAfter: oneHour
});

这会使用connect-mongo创建一个mongoDB商店 - 我确信这也可以用mongoose完成,但我不知道如何将它作为练习留给读者: - )

然后你可以告诉快递会议模块使用这个商店:

app.use(expressSession({
  secret: serverConfig.sessionSecret,
  store: sessionStore,    // <---- added store information!
  resave: false,
  saveUninitialized: false
}));