如何正确重新生成会话 ID?
我已经构建了一个会话库,并且遇到了一个非常随机的错误(我真的不知道如何对其进行单元测试,所以我只是用日志消息填充所有内容并等待它再次发生),该错误转换为正在记录的用户由于会话 ID 不匹配而退出。
应用程序的流程如下:
- 发出具有有效会话 ID 的请求
- 在数据库中找到该会话 ID 的会话数据
- “最后一个活动”恰好是旧的,因此在数据库中重新生成并更新它
- 新的活动会话 ID 在响应中发送(作为 cookie)
这几乎总是可以正常工作,但有时下一个请求无法匹配会话 ID,因为(这是我的猜测)它是在我们更新数据库后发送的(在上一个请求中) ,仍在运行),但在响应之前新的 cookie 进来了。
我是否误解了重新生成会话 ID 的概念?我只是出于安全原因重新生成会话 ID,因此选择登录一年的人的会话 ID 仍然会不时更改。
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 before 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种选择是为每个用户保留多个会话 ID,但在它们上设置过期时间 - 当需要重新生成会话 ID 时,添加新会话 ID,并在旧会话 ID 上设置等于某个合理时间段的过期时间(也许一分钟)。除了新的,还要继续接受旧的,直到旧的过期。
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.
我假设您正在使用
session_set_save_handler()
,对吧..?如果是这样,请尝试执行以下操作:或者甚至:
调用
session_write_close()
应该有效保存新的会话数据。您只需在调用此函数时注意(通常在权限更改>重定向之前),因为它会结束会话。I assume you're using
session_set_save_handler()
, right..? If so, try doing the following:Or even:
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.