Reputation: 1012
I'm trying to implement Express and Passport sessions like so:
app.use(connect.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
cookie: {
path: "/",
httpOnly: true,
maxAge: null
},
store: redisStoreConnect,
secret: "something",
key: 'pksy.sid'
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser (user, done) ->
done null, user.email
return
passport.deserializeUser (email, done) ->
User.findOne
email: email
, (err, user) ->
done err, user
return
return
If I navigate to a page in my site, a new session is created and stored in redis. If I refresh that page, the session appears to persist. If I navigate to a new page or even if I close the tab and reopen to the same page, a new session is created.
This is especially frustrating since Passport only authenticates the session that was generated for my login page. How do I get my sessions to persist across pages?
Update: Thanks @robertklep for reminding me to check what cookie the browser was actually sent back (which I should have done to start). It turns out the browser is sending back the right cookie, and the authentication is working. The sessions are in fact persisting, but for some reason a new session (unused by the browser) gets created with each page request. How can I stop this?
Upvotes: 1
Views: 4561
Reputation: 10674
In my case I have to use
app.use(passport.initialize());
app.use(passport.session());
before
app.use(app.router);
Hope this can help.
Upvotes: 0
Reputation: 1012
"Oh, you didn't know the browser doesn't send the session cookie with the request for the favicon?" says my roomate the hacker, whose ilk created the need for the following single line of code.
11 hours of debugging later here is what solved the problem:
app.use express.favicon()
Express was treating the favicon like any other resource, while the browser was making a specialized, apparently cookieless request for it. Express assumed this request must have come from a client without a session cookie, so it created a new session for them; a session never to be called upon again. express.favicon()
saves the day!
Upvotes: 4