记住我的最佳做法功能

mTu*_*ran 8 php cookies remember-me autologin

我在cookie中使用了2个变量(7天到期),即用户ID和哈希值.哈希是用户代理和用户ID的sha1编码.在这种情况下,一些黑客可以登录谁知道被盗cookie的浏览器.我应该遵循哪种方式或哪种方法最适合记住我的安全问题?

Som*_*ere 6

虽然您可以散列user_id和secret_key,但拦截此cookie的任何人都可以登录您的应用程序.除此之外,你可以做到这一点,以便你记住我的饼干很快就会陈旧.没人喜欢陈旧的饼干.

您可以将每个用户上次访问的时间戳存储在数据库和cookie中.每次读取cookie以记录用户时,都会检查两个时间戳是否匹配.如果他们不这样做,则拒绝用户.如果是,请更新时间戳.

使用此方法,只要您的用户返回您的网站,所有旧Cookie都会过时.截获cookie的黑客现在拥有一个毫无价值的陈旧cookie,因为他不知道当前cookie中的确切时间戳.当然,黑客可以根据需要使用新鲜的cookie,直到用户重新登录.

//check for cookie
if(isset($_COOKIE['remember_me'])) {
   // get hash and time stamp from cookie
   $hash = substr($_COOKIE['remember_me'],0,40);
   $last_visit = substr($_COOKIE['remember_me'],41);

   // query your db with $hash and $last_visit

   // if hash and time stamp match up
      // log in

      // store the current time stamp in a variable to use for both
      $time = date("Y-m-d H:i:s");
      // update the time stamp in your cookie
      $cookie = $pass . "-" . $time;
      setcookie('remember_me', $cookie, time()+60*60*24*100, '/');
      // update the time_stamp in your database
   else {
      // remove the remember me cookie
      setcookie('remember_me', '', time()-42000, '/')
   }
Run Code Online (Sandbox Code Playgroud)

这种方法提供了少量的安全性,当然也应该与其他答案中提出的方法一起使用.散列密钥应存储在cookie中.记住我的cookie不能完全安全,因此对于高度敏感的数据或应用程序功能的任何其他访问都需要密码重新输入.

我还建议在"remember_me"之外命名你的cookie,使其更难找到.虽然它没有增加太多的安全性,但如果有的话,命名你的'ht33424'就需要命名'remember_me'或'hack_me'.