Session IDs don't persist unless passport.js is initialized

社会主义新天地 提交于 2019-12-13 02:25:43

问题


I have a simple, generic express app. It logs the req.sessionID whenever a certain route is hit. I would expect that refreshing the client page would result in the same sessionID being logged again. This works, if I've imported passport and added the passport middleware after the session middleware. If I either don't use passport at all, or I add passport middleware before the session middleware, then the sessionID is different every time.

I can accept that the ordering of middleware can be finicky. However, my app doesn't use passport at all, so I can't fathom why my app doesn't work if I don't require passport. Should passport be necessary for sessions to work?

    //generic express initialization
    var http = require('http');
    var express = require('express');
    var cookieParser = require('cookie-parser');
    var passport = require('passport');
    var session = require('express-session');

    var app = express();
    var server = http.createServer(app);
    var sessionMiddleware = session({resave: false, saveUninitialized: false, secret: 'hunter2'});
    app.use(cookieParser());


    //This works:
    app.use(sessionMiddleware);
    app.use(passport.initialize());

    //This doesn't:
    app.use(passport.initialize());
    app.use(sessionMiddleware);

回答1:


Switch to resave: true, saveUninitialized: true

Unmodified sessions were not being saved, thus resulting in repeatedly generating new session IDs. Passport, however, was presumably doing some initialization on the session, meaning that the session was no longer unmodified.

Thanks to @Dodekeract and @Swaraj Giri for figuring the issue in their comments!



来源:https://stackoverflow.com/questions/31375964/session-ids-dont-persist-unless-passport-js-is-initialized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!