Search code examples
phpcookiesremember-meautologin

Best practice for remember me feature


I am using 2 variables in cookie (7 day expiration) which is user id and hash. Hash is sha1 encode of user agent and user id. In this case some hacker can login who is know stolen cookie's browser. Which way should I follow or which practice is best for remember me security problems?


Solution

  • While you can hash a user_id and secret_key, anyone who intercepts this cookie can log in to your application. In addition to this, you can make it so that your remember me cookies go stale very quickly. No one likes a stale cookie.

    You can store the time stamp of each user's last visit in your database and in the cookie. Each time you read the cookie to log the user in, you check to see that both timestamps match. If they don't, deny the user. If they do, update the timestamps.

    Using this method, any time your user returns to your site, all old cookies go stale. A hacker that has intercepted a cookie now has a worthless stale cookie because he does not know the exact time stamp in the current cookie. Of course, the hacker can use a fresh cookie as much as he wants until the user logs back in.

    //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, '/')
       }
    

    This method offers a small amount of security, and should certainly be used along side methods proposed in other answers. A hashed key should be stored in the cookie. A remember me cookie cannot be perfectly secure, so password re-entry should be required for any additional access to highly sensitive data or application features.

    I also recommend naming your cookie something besides 'remember_me' to make it a little harder to find. While it does not add much security, if any, naming your cookie 'ht33424' takes just as long as naming it 'remember_me' or 'hack_me'.