How to save a Passport NodeJS session

We are Node + Express + Passport for authentication and save session information for Redis. I have maxAge set in a session cookie to disconnect after one hour. Everything seems to be working fine, but the problem is that the session cookie will expire after one hour, regardless of user activity.

Is there a way to manually update / save a session cookie?

+6
source share
4 answers

You will probably want to use the rollback option for your session. This "forces the cookie to set on every response" and "resets expiration date". You want to set the switch to true.

Also note the "resave" parameter. This means that the session will be saved even if it is unmodified ... "You will probably want to set this option to true as well. Note that although the default value for this option is true, you must explicitly set the value. Based on the default value for this parameter, instead of explicitly specifying it, it is now deprecated.

Try something like:

app.use( session( { secret: 'keyboard cat', cookie: { maxAge: 60000 }, rolling: true, resave: true, saveUninitialized: false } ) ); 

Here is the documentation. Take a look in the "Options" and "options.resave" sections: https://github.com/expressjs/session .

+5
source

Yes, you can! If the cookie remains unchanged upon request, it will not be re-sent to the browser, you can check the developer tools under the cookies to make sure. So some, including myself, how to do this, change the cookie on request, where there is user activity that should extend the session. Something like the following:

req.session.lastAccess = new Date().getTime();

Another thing I saw, but I had problems using Session # touch :

req.session.touch()

+4
source

Yes, you can manually reset maxAge for each cookie after a user logs in:

 req.session.cookie.maxAge = 60 * 60 * 1000; 

Here's the connect session documentation .

0
source

Try this code:

app.use(session({ secret: 'Category', cookie: { maxAge: 6000000 }, resave: true, saveUninitialized: false}));

0
source

Source: https://habr.com/ru/post/959349/


All Articles