PHP 使用 Cookie 将当前会话 ID 存储在数据库中 [英] PHP Storing Current Session IDs in Database using Cookies

查看:61
本文介绍了PHP 使用 Cookie 将当前会话 ID 存储在数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个登录系统,它使用 cookie 并将会话 ID 存储在数据库中,因此您的登录只能使用该特定会话 ID.我意识到这有几个问题:

  1. 如果您在另一台设备上登录,会话 ID 会发生变化(没有多次登录)
  2. 会话 ID 实际上是唯一标识用户已登录的信息(我不确定这是否存在安全风险,因为 cookie 是特定于域的)

但是,我想保留 cookie 附带的持久登录,同时仍然保持安全.

实际上,我想知道是否有更好的方法来使用 cookie 安全地将用户登录到网站.

解决方案

首先,保持安全和持久登录不能同时进行;以某种方式引入持久登录总是会损害安全性.

话虽如此,Charles Miller 的文章概述了这样一个系统:

  1. 创建一个(足够大的)随机密钥,最好使用 /dev/urandomopenssl_random_pseudo_bytes() 并将其与帐户相关联(在数据库术语中):一个单独的表,随机键作为主(或唯一)索引,账户作为外键);键将是 cookie 值.

  2. 当未登录用户提交cookie时,查找key和账号,用户登录;之后,使用的密钥将替换为新的随机密钥(cookie 也会更新).

  3. 仅通过 cookie 登录的用户在访问敏感(帐户)信息时应再次要求输入密码.

  4. 用户应该可以选择退出他的所有设备.

每当用户登录(通过表单或 cookie)时,使用 session_regenerate_id() 更新会话 ID 也是一个好习惯.这可以防止某人对其他人发起会话固定攻击并可能窃取他们的身份.

可以在此处找到 Barry Jaspen 对此设计的改进,该改进还可以处理身份盗窃检测.>

I've created a login system that uses cookies and stores a session ID in a database, so your login will only work with that particular session ID. I realise this has a few problems:

  1. If you login on another device the session ID changes (no multi logins)
  2. The session ID is really the only thing identifying the user as logged in (I'm not really sure if this is a security risk since the cookie is domain specific)

However I want to retain the persistant login that comes with cookies while still keeping stuff secure.

Effectively I want to know if there is a better way to securely log a user into a website using cookies.

解决方案

First of all, keeping stuff secure and persistent logins don't go together; you will always compromise security by introducing persistent logins in some way.

Having said that, an article from Charles Miller outlines such a system:

  1. create a (big enough) random key, preferably by using /dev/urandom or openssl_random_pseudo_bytes() and associate it with an account (in database terms: a separate table with the random key as the primary (or unique) index and the account as a foreign key); the key will be the cookie value.

  2. when a non-logged in user presents a cookie, the key and account are looked up and the user is logged in; afterwards, the used key is replaced with a new random key (cookie is updated too).

  3. users who are logged in via cookie alone should be asked for their password again when they access sensitive (account) information.

  4. the user should have an option to log out from all his devices.

It's also a good practice to use a renew the session id using session_regenerate_id() whenever a user is logged in (either via a form or cookie). This prevents someone from launching a session fixation attack against someone else and possibly steal their identity.

An improvement on this design by Barry Jaspen that can also handle identify theft detection can be found here.

这篇关于PHP 使用 Cookie 将当前会话 ID 存储在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆