开发者

How to properly regenerate session ID's?

开发者 https://www.devze.com 2023-03-03 01:02 出处:网络
I have built a session library, and I am having a very random bug (I don\'t really know how to unit test this, so I just filled everything with log messages and waited till it happened again) that tra

I have built a session library, and I am having a very random bug (I don't really know how to unit test this, so I just filled everything with log messages and waited till it happened again) that translates into a user being logged out, due to a session ID mismatch.

The flow of the application goes like this:

  • A request with a valid session ID is made
  • Session data is found for that session ID in the DB
  • The 'last activity' happens to be old, so it is regenerated and updated in the DB
  • The new session ID is sent in the response (as a cookie)

This works fine almost always, but sometimes the next request fails to match the session ID, because (this is my guess) it was sent after we updated the database (in the previous request, which was still running), but befo开发者_运维百科re the response with the new cookie came in.

Did I misunderstand the concept of regenerating a session ID? I'm regenerating session ID's only for security reasons, so someone that chose to be logged in for a year, still has his session ID changed from time to time.


One option would be to keep multiple session ids per user, but put expiry times on them - when it's time to regenerate a session id, add the new one, and put an expiry time on the old one equal to some reasonable period of time (a minute, perhaps). Keep accepting the old one in addition to the new one until the old one expires.


I assume you're using session_set_save_handler(), right..? If so, try doing the following:

session_regenerate_id($delete_old_session = true);
session_write_close();

Or even:

session_regenerate_id($delete_old_session = false);
session_write_close();

Calling session_write_close() should effectively save the new session data. You only have to pay attention when you call this (usually before privilege changes > redirects), since it ends the session.


End the current session and store session data.

Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time.

0

精彩评论

暂无评论...
验证码 换一张
取 消