将用户信息保存在 Cookie 中


Saving User Information in a Cookie

当用户选择记住我功能时,我会将他的用户名和ID保存在cookie中。然后,当用户返回站点时,我会根据数据库检查用户名和密码,以确保用户是合法的。接下来,我通过将 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 已过期。

查询以检查登录

从 记住我中选择 * 键="//把 md5 放在这里"并且有效直到> 时间()

No.

这取决于您想要获得的安全性。 以下是您可以执行的一些操作(部分或全部)以提高安全性:

  • 不要在 Cookie 中存储任何特定内容(用户名/ID/等)。 使用随机生成的废话(令牌)。
    1. 在数据库中,您可以拥有令牌<>用户映射
    2. 对照数据库检查令牌,并在匹配时登录用户
    3. 销毁令牌(将其标记为"已使用",也许稍后会删除。 无论您决定什么,令牌都不应该再起作用了)。
  • 仅使用https来传输 Cookie、登录等。
  • 如果用户发送过时的令牌(即不在数据库中的令牌,或已标记为已使用的令牌),则意味着令牌可能已泄露。 在对经过身份验证的用户(甚至可能使用 ajax)的每个请求中,将他们登录时使用的令牌(您可以将其存储在会话中)与过时的令牌尝试列表进行比较。 如果存在匹配项,则意味着经过身份验证的用户可能劫持了令牌。 把他们踢出去。