我的web应用程序使用会话存储关于用户的信息,一旦他们登录,并维护这些信息,因为他们在应用程序内从页面到页面。在这个特定的应用程序中,我存储的人的user_id, first_name和last_name。
我想在登录时提供一个“让我登录”选项,在用户的机器上放置一个cookie,为期两周,当他们返回应用程序时,将以相同的细节重新启动他们的会话。
做这件事的最佳方法是什么?我不想在cookie中存储他们的user_id,因为这似乎会让一个用户很容易尝试和伪造另一个用户的身份。
我的web应用程序使用会话存储关于用户的信息,一旦他们登录,并维护这些信息,因为他们在应用程序内从页面到页面。在这个特定的应用程序中,我存储的人的user_id, first_name和last_name。
我想在登录时提供一个“让我登录”选项,在用户的机器上放置一个cookie,为期两周,当他们返回应用程序时,将以相同的细节重新启动他们的会话。
做这件事的最佳方法是什么?我不想在cookie中存储他们的user_id,因为这似乎会让一个用户很容易尝试和伪造另一个用户的身份。
当前回答
我认为你可以这样做:
$cookieString = password_hash($username, PASSWORD_DEFAULT);
将$cookiestring存储在DB中,并将其设置为cookie。还要将用户名设置为cookie。哈希的全部意义在于它不能被逆向工程。
当用户出现时,从一个cookie中获取用户名,然后从另一个cookie中获取$cookieString。如果$cookieString与存储在DB中的匹配,则验证用户的身份。由于password_hash每次使用不同的盐,所以它与明文是什么无关。
其他回答
我在这里问了这个问题的一个角度,答案将引导您找到所需的所有基于令牌的超时cookie链接。
基本上,您不会将userId存储在cookie中。您存储了一个一次性令牌(巨大的字符串),用户使用它来拾取旧的登录会话。然后,为了使其真正安全,在进行重大操作(比如更改密码本身)时,需要输入密码。
旧的线程,但仍然是一个有效的关注。我注意到一些关于安全性的很好的回答,并避免使用“通过模糊实现安全性”,但在我看来,给出的实际技术方法还不够。在我提出我的方法之前,我必须说:
NEVER store a password in clear text...EVER! NEVER store a user's hashed password in more than one location in your database. Your server backend is always capable of pulling the hashed password from the users table. It's not more efficient to store redundant data in lieu of additional DB transactions, the inverse is true. Your Session ID's should be unique, so no two users could ever share an ID, hence the purpose of an ID (could your Driver's License ID number ever match another persons? No.) This generates a two-piece unique combination, based on 2 unique strings. Your Sessions table should use the ID as the PK. To allow multiple devices to be trusted for auto-signin, use another table for trusted devices which contains the list of all validated devices (see my example below), and is mapped using the username. It serves no purpose to hash known data into a cookie, the cookie can be copied. What we are looking for is a complying user device to provide authentic information that cannot be obtained without an attacker compromising the user's machine (again, see my example). This would mean, however, that a legitimate user who forbids his machine's static information (i.e. MAC address, device hostname, useragent if restricted by browser, etc.) from remaining consistent (or spoofs it in the first place) will not be able to use this feature. But if this is a concern, consider the fact that you are offering auto-signin to users whom identify themselves uniquely, so if they refuse to be known by spoofing their MAC, spoofing their useragent, spoofing/changing their hostname, hiding behind proxies, etc., then they are not identifiable, and should never be authenticated for an automatic service. If you want this, you need to look into smart-card access bundled with client-side software that establishes identity for the device being used.
话虽如此,在系统上有两种自动登录的好方法。
First, the cheap, easy way that puts it all on someone else. If you make your site support logging in with, say, your google+ account, you probably have a streamlined google+ button that will log the user in if they are already signed into google (I did that here to answer this question, as I am always signed into google). If you want the user automatically signed in if they are already signed in with a trusted and supported authenticator, and checked the box to do so, have your client-side scripts perform the code behind the corresponding 'sign-in with' button before loading, just be sure to have the server store a unique ID in an auto-signin table that has the username, session ID, and the authenticator used for the user. Since these sign-in methods use AJAX, you are waiting for a response anyway, and that response is either a validated response or a rejection. If you get a validated response, use it as normal, then continue loading the logged in user as normal. Otherwise, the login failed, but don't tell the user, just continue as not logged in, they will notice. This is to prevent an attacker who stole cookies (or forged them in an attempt to escalate privileges) from learning that the user auto-signs into the site.
这很便宜,也可能被一些人认为是肮脏的,因为它试图在不告诉你的情况下,在谷歌和Facebook等地方验证你可能已经登录的自我。然而,它不应该用于那些没有要求自动登录您的网站的用户,这种特殊的方法仅用于外部身份验证,如谷歌+或FB。
由于使用外部验证器在幕后告诉服务器用户是否经过验证,因此攻击者只能获得唯一ID,而唯一ID本身是无用的。我将详细说明:
User 'joe' visits site for first time, Session ID placed in cookie 'session'. User 'joe' Logs in, escalates privileges, gets new Session ID and renews cookie 'session'. User 'joe' elects to auto-signin using google+, gets a unique ID placed in cookie 'keepmesignedin'. User 'joe' has google keep them signed in, allowing your site to auto-signin the user using google in your backend. Attacker systematically tries unique IDs for 'keepmesignedin' (this is public knowledge handed out to every user), and is not signed into anywhere else; tries unique ID given to 'joe'. Server receives Unique ID for 'joe', pulls match in DB for a google+ account. Server sends Attacker to login page that runs an AJAX request to google to login. Google server receives request, uses its API to see Attacker is not logged in currently. Google sends response that there is no currently signed in user over this connection. Attacker's page receives response, script automatically redirects to login page with a POST value encoded in the url. Login page gets the POST value, sends the cookie for 'keepmesignedin' to an empty value and a valid until date of 1-1-1970 to deter an automatic attempt, causing the Attacker's browser to simply delete the cookie. Attacker is given normal first-time login page.
无论如何,即使攻击者使用了不存在的ID,除了接收到经过验证的响应外,所有尝试都应该失败。
对于那些使用外部验证器登录到站点的用户,此方法可以而且应该与内部验证器结合使用。
= = = = = = = = =
现在,对于您自己的可以自动登录用户的验证器系统,我是这样做的:
DB有几个表:
TABLE users:
UID - auto increment, PK
username - varchar(255), unique, indexed, NOT NULL
password_hash - varchar(255), NOT NULL
...
注意,用户名的长度可以是255个字符。我的服务器程序将系统中的用户名限制为32个字符,但外部身份验证者可能使用@域作为用户名。tld要比这个大,所以我只支持电子邮件地址的最大长度,以获得最大的兼容性。
TABLE sessions:
session_id - varchar(?), PK
session_token - varchar(?), NOT NULL
session_data - MediumText, NOT NULL
Note that there is no user field in this table, because the username, when logged in, is in the session data, and the program does not allow null data. The session_id and the session_token can be generated using random md5 hashes, sha1/128/256 hashes, datetime stamps with random strings added to them then hashed, or whatever you would like, but the entropy of your output should remain as high as tolerable to mitigate brute-force attacks from even getting off the ground, and all hashes generated by your session class should be checked for matches in the sessions table prior to attempting to add them.
TABLE autologin:
UID - auto increment, PK
username - varchar(255), NOT NULL, allow duplicates
hostname - varchar(255), NOT NULL, allow duplicates
mac_address - char(23), NOT NULL, unique
token - varchar(?), NOT NULL, allow duplicates
expires - datetime code
MAC addresses by their nature are supposed to be UNIQUE, therefore it makes sense that each entry has a unique value. Hostnames, on the other hand, could be duplicated on separate networks legitimately. How many people use "Home-PC" as one of their computer names? The username is taken from the session data by the server backend, so manipulating it is impossible. As for the token, the same method to generate session tokens for pages should be used to generate tokens in cookies for the user auto-signin. Lastly, the datetime code is added for when the user would need to revalidate their credentials. Either update this datetime on user login keeping it within a few days, or force it to expire regardless of last login keeping it only for a month or so, whichever your design dictates.
This prevents someone from systematically spoofing the MAC and hostname for a user they know auto-signs in. NEVER have the user keep a cookie with their password, clear text or otherwise. Have the token be regenerated on each page navigation, just as you would the session token. This massively reduces the likelihood that an attacker could obtain a valid token cookie and use it to login. Some people will try to say that an attacker could steal the cookies from the victim and do a session replay attack to login. If an attacker could steal the cookies (which is possible), they would certainly have compromised the entire device, meaning they could just use the device to login anyway, which defeats the purpose of stealing cookies entirely. As long as your site runs over HTTPS (which it should when dealing with passwords, CC numbers, or other login systems), you have afforded all the protection to the user that you can within a browser.
One thing to keep in mind: session data should not expire if you use auto-signin. You can expire the ability to continue the session falsely, but validating into the system should resume the session data if it is persistent data that is expected to continue between sessions. If you want both persistent AND non-persistent session data, use another table for persistent session data with the username as the PK, and have the server retrieve it like it would the normal session data, just use another variable.
Once a login has been achieved in this way, the server should still validate the session. This is where you can code expectations for stolen or compromised systems; patterns and other expected results of logins to session data can often lead to conclusions that a system was hijacked or cookies were forged in order to gain access. This is where your ISS Tech can put rules that would trigger an account lockdown or auto-removal of a user from the auto-signin system, keeping attackers out long enough for the user to determine how the attacker succeeded and how to cut them off.
最后注意,确保任何恢复尝试、密码更改或超过阈值的登录失败都会导致自动登录被禁用,直到用户正确验证并确认发生了这种情况。
如果有人期望在我的回答中给出代码,我很抱歉,这不会发生在这里。我会说我使用PHP, jQuery和AJAX来运行我的网站,我从不使用Windows作为服务器…永远。
我读了所有的答案,仍然发现很难提取我应该做什么。如果一张图片相当于1k个单词,我希望这有助于其他人实现基于Barry Jaspan的改进的持久登录Cookie最佳实践的安全持久存储
如果您有问题、反馈或建议,我将尝试更新图表,以反映试图实现安全持久登录的新手。
安全注意:基于确定性数据的MD5哈希的cookie是一个坏主意;最好使用从CSPRNG派生的随机令牌。有关更安全的方法,请参阅ircmaxell对这个问题的回答。
通常我会这样做:
User logs in with 'keep me logged in' Create session Create a cookie called SOMETHING containing: md5(salt+username+ip+salt) and a cookie called somethingElse containing id Store cookie in database User does stuff and leaves ---- User returns, check for somethingElse cookie, if it exists, get the old hash from the database for that user, check of the contents of cookie SOMETHING match with the hash from the database, which should also match with a newly calculated hash (for the ip) thus: cookieHash==databaseHash==md5(salt+username+ip+salt), if they do, goto 2, if they don't goto 1
当然,你可以使用不同的cookie名称等,你也可以改变cookie的内容,只是要确保它不容易创建。例如,你也可以在创建用户时创建user_salt,并将其放在cookie中。
你也可以用sha1代替md5(或者几乎任何算法)
我推荐Stefan提到的方法(即遵循改进的持久登录Cookie最佳实践中的指导方针),也建议你确保你的Cookie是HttpOnly Cookie,这样它们就不会被潜在的恶意JavaScript访问。