【问题标题】:Sessions on two local Node.js servers两个本地 Node.js 服务器上的会话
【发布时间】:2017-08-17 16:35:55
【问题描述】:

我有两个本地 Node.js 服务器:

  1. http://localhost:3000

  2. http://localhost:3001

我使用 express.js 和 passport.js 进行身份验证。身份验证工作正常,但是如果:

  1. 我在服务器 1 上登录
  2. 我在服务器 2 上登录

然后服务器 1 上的会话消失。如何防止这种情况发生?

app.use(bodyParser());
app.use(cookieParser());
app.use(session({
secret: '12345',
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());


passport.use(new LocalStrategy(
function(username, password, done) {
  users.getActiveByUsername(username, function(err, user) {
    if (err) {console.log(err); return done(err); }
    if (!user) {
      return done(null, false, { message: 'Incorrect username' });
    }
    if (user.password != password) {
      return done(null, false, { message: 'Incorrect password' });
    }
    return done(null, user);
  });
}
));

passport.serializeUser(function(user, done) {
done(null, user);
});

passport.deserializeUser(function(user, done) {
done(null, user);
});

app.post("/login", jsonParser, function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
  if (err) { return next(err); }
  if (!user) { res.status(400).send('Wrong username or password');return; }
  req.logIn(user, function(err) {
    if (err) { return next(err); }
    return res.json({'success':'Successful login'});
  });
})(req, res, next);
});

【问题讨论】:

  • 请提供一些代码,特别是您处理会话的地方。
  • 我相信你必须将会话cookie存储在像Redis这样的外部存储中,并检查每个Node.js服务器内用户会话的有效性。
  • @KayvanMazaheri 添加了代码
  • @Artem session的有效性由passport.js检查,你能提供更多细节吗?

标签: node.js session express passport.js


【解决方案1】:

我假设您为两个应用程序使用相同的数据库。

默认情况下,您无法将具有相同主机名的不同应用的会话保存在同一数据库中。您必须通过使用不同的名称或前缀来区分它们。

如果您使用express-session 处理您的会话,您可以通过选项设置不同的名称:

app.use(session({
  secret: '12345',
  resave: true,
  saveUninitialized: true,
  name: 'app1'          // use a different name for the second app
}));

阅读official documentationexpress-session 了解更多信息。

注意
如果您有多个应用程序在同一个主机名上运行(这只是名称,即localhost127.0.0.1;不同的方案和端口不会命名不同的主机名),那么您需要将会话 cookie 彼此分开。最简单的方法是为每个应用设置不同的names

【讨论】:

  • 感谢您的回答
猜你喜欢
  • 2017-12-26
  • 2018-06-23
  • 2019-03-10
  • 1970-01-01
  • 2021-10-29
  • 2014-12-05
  • 1970-01-01
  • 2011-07-14
  • 1970-01-01
相关资源
最近更新 更多