How to keep alive an NodeJS Passport session

馋奶兔 提交于 2020-01-22 18:56:27

问题


We're Node + Express + Passport for authentication, and persisting the session info to Redis. I have maxAge set on the session cookie, to time out in one hour. That all seems to be working fine but the problem is, the session cookie will expire in one hour regardless of the user's activity.

Is there a way I can manually refresh/keep alive the session cookie?


回答1:


You'll likely want to use the "rolling" option for your session. This "forces a cookie set on every response" and "resets the expiration date." You want to set rolling to true.

Also pay attention to the "resave" option. That "forces session to be saved even when unmodified..." You'll likely want to set that option to true as well. Note that even though the default value is true for this option, you should set the value explicitly. Relying on the default for this option, rather than setting it explicitly, is now deprecated.

Try something like:

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

Here's the documentation. Look under "Options" and "options.resave": https://github.com/expressjs/session .




回答2:


Yes you can! If the cookie is unchanged on a request then it will not be resent to the browser, you can check in the developer tools under cookies to verify that. So what some, including myself like to do is to 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've seen but I've had trouble with is to use the Session#touch:

req.session.touch()




回答3:


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

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

Here is the connect session documentation.




回答4:


Try this code:

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



来源:https://stackoverflow.com/questions/20387554/how-to-keep-alive-an-nodejs-passport-session

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