【发布时间】:2012-06-28 01:11:46
【问题描述】:
当用户选择记住我功能时,我会将他的用户名和 ID 保存在 cookie 中。然后,当用户返回站点时,我会根据数据库检查用户名和 ID,以确保用户是合法的。接下来,我通过将 cookie 数据存储在会话变量中来登录用户。这是记住和登录用户的正确方法吗?
【问题讨论】:
当用户选择记住我功能时,我会将他的用户名和 ID 保存在 cookie 中。然后,当用户返回站点时,我会根据数据库检查用户名和 ID,以确保用户是合法的。接下来,我通过将 cookie 数据存储在会话变量中来登录用户。这是记住和登录用户的正确方法吗?
【问题讨论】:
Cookie 不是一种非常安全的数据存储方式。 cookie 可以由用户修改,并可能导致某人“入侵”您的网站。我建议在 cookie 中存储一个字符串,该字符串是某种东西的哈希值。还将来自 cookie 的散列字符串存储在数据库中。这样,当用户返回站点时,您检查 cookie 是否已填充,将其与数据库中的散列值相匹配,然后找出谁拥有该散列值。如果一切都有效,请登录。
数据库设置
secretKey PK varchar
userid (could be unique) int
validUntil int or date/time
//If userID is unique you will have to remove this row from the
// database when a new key is made for the user, This would then mean
// that a user would only be allowed to be rememberd on one computer
伪代码
//User logs in with remember me
//set cookie to something like md5(userid,username,timestamp)
//store the md5 in the database layout
//User Returns to site
//check to see if cookie is set
//if cookie set
//find md5 in database which is logged with user id
//if found and not yet expired log in
//else show login page
//if cookie not set show login page
在有效截止日期字段中,您可以将其设置为登录后 2 周。一旦有效截止时间已过,请不要让该密钥起作用,并确保 cookie 对用户而言已过期。
查询以检查登录
SELECT * FROM rememberMe WHERE key="//put md5 here" AND validUntil > time()
【讨论】:
没有。
这取决于您想要获得的安全程度。以下是您可以采取的一些措施(部分或全部)来提高安全性:
https 仅用于传输 cookie、登录等。【讨论】: