2012-06-27 124 views
1

当用户选择记住我功能时,我将其用户名和ID保存在cookie中。然后,当用户返回到站点时,我检查数据库的用户名和ID以确保用户是合法的。接下来通过将cookie数据存储在会话变量中来登录用户。这是记住和登录用户的正确方法吗?将用户信息保存在Cookie中

+0

http://stackoverflow.com/questions/2594960/best-practice-to-implement-secure-remember-me –

回答

3

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其中key = “//把MD5这里” 和validUntil>时间()

+0

好吧,我明白你在说什么,但我要如何处理validUntil场?当日期过去后我该怎么办? – user532493

+0

立即看到新帖子 – bretterer

+0

这个secretKey字段应该与我的所有用户在表中,还是应该有一个用于secretKey的新表? – user532493

2

这取决于到底有多安全你想得到。以下是您可以做的一些事情(部分或全部)以提高安全性:

  • 不要在cookie(用户名/ ID /等)中存储任何特定的内容。使用随机生成的废话(令牌)。
    1. 在你的数据库,你可以有一个令牌< - >用户映射
    2. 检查令牌对你的数据库并登录时,有一个匹配
    3. 销毁令牌(标志为“消耗”,或许用户稍后会被删除,不管你决定什么,令牌都不应该再起作用了)。
  • 使用https如果用户发送一个陈旧的令牌(即一个,是不是在你的数据库,或已被标记为消费)只发送的cookie,登录等
  • 这意味着它令牌可能已被泄露。在每个对经过身份验证的用户的请求中(甚至可能使用ajax),将它们登录的令牌(可以存储在会话中)与一个陈旧的令牌尝试列表进行比较。如果匹配,这意味着认证用户可能劫持了令牌。踢出来。
+1

好的,非常感谢你的所有建议。 – user532493