开发者

What is the most secure way to do a cookie based "Stay logged in"?

what is the securest way to do a "stay logged in" feature?

i think thinking of user logs in store their userid, timestamp and a hash of timestamp + salt + hash of their pw in a cookie. then when they visit the site next, check if a hash of the cookie timestamp + salt + hash of their pw is valid

(ie... (untested, and ignore lack of mysql_real_escape_string())

(this is in php)

 /*
 cookie contains 开发者_C百科these fields:
 username
 timestamp
 hash
 */

 $row  = mysql_fetch_array($result); 
            ## sql would be something like select salt,
            ## username from users where user = $_COOKIE['username']

 $generated_cookie_data = my_hash_func(
            $_COOKIE['timestamp'] . 
            $row['salt_from_db'] .
             my_hash_func([$row['password'])
             )

 if ($generated_cookie_data == $_COOKIE['hash']) {
 #logged in!
 }
 else {
 #not logged in!
 }


Most likely you should not do this yourself - reinventing the wheel will get you a bad wheel. Use whatever session management your web programming frameworks provide. What, you're not using a framework? Then you're mad, and I wish you luck.


Just generate a long, pure random and unique ID. Don't matter how, there is absolutely no need to base it on salt+password+IP, it only absolutely must not have a pattern (i.e. don't use IP, timestamp, etc). Have a database table user_session with the columns session_id (PK) and user_id (FK) (and if necessary more, like session_ttl, user_ip and so on). Generate a session ID and check if it exist in the table. If not, then save it along with the user ID in the table. Store the very same session ID in a long living cookie and check it on every new request.


I think you should include the IP address in the hash. That way, if another user somehow stole the cookie, they wouldn't have access to the session.

A more secure method would be to generate a random ID each time the user logs in and store that in the user table. Then hash random + salt + password + ip.


IMO you should never reveal information about the users password (even a hash). If someone got access to this hash they can try as many times as they like at guessing the users password. They are not limited by any security mechanisms you have to protect accounts from random guessing.

If I were using the approach you describe I would at least create a random number that is stored in he db instead of using the password.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜