Reputation: 2900
I know this question may be asked many times but most of them suggests you to store ip+username+password and hash this whole thing and compare, instead I came up with a different solution for my website, I want to do something like this:
Am using session to store username, userid, timezone offset etc, now suppose we say a user logs in and he checked remember me, I'll set sessions and then I'll generate an variable uniqueid holding random 12-13 digit ID, after setting this I'll create a cookie using this unique ID and username on his browser and also store it in my database and when he comes back I'll check whether that id and username cookie is set if yes than select username, remembermeid from database where username=cookie username and than set sessions again and throw him on the homepage else redirect to login page..
If he logs out I'll delete all cookies and will update the unique value back after he selects remember and logs in...
Any problem in doing this? or a better way to do it? I don't want password to be saved in cookie, even in a hashed state..or what am doing is perfect?
Upvotes: 2
Views: 1154
Reputation: 50328
So, as I understand your description, when a user logs in (and wishes to remain permanently logged in), you do the following:
When the user returns and does not have an active session, but does have the cookies set above, you look up their username in the database. If the database contains a "remember me" token for that user, and the token matches the one in the cookie, you create a new session for the user.
When the user logs out, you delete the cookies from their browser and also delete the token from the database.
If so, that's a perfectly safe design, as long as the token is long enough and generated by a secure random number generator (like /dev/urandom
on Unix). You say your tokens are "12-13 digits long", which translates to a little over 40 bits; that's a bit on the low side, I'd recommend at least twice that. Also, you don't say how you're generating the tokens; just using PHP's rand
or mt_rand
isn't safe, as their output may be predictable.
I would also suggest two improvements: First, hash the token before storing it in the database (any cryptographic hash function will do, e.g. SHA-1 — with long random tokens you don't need any special password-hashing function like PBKDF2) so that an attacker who manages to copy the database won't get all the tokens. Second, include an expiration date for the tokens in the database, so that a single compromised token won't remain valid forever.
Upvotes: 3
Reputation: 17285
You never have to store username and/or password in cookies. All you need to store is one unique identificator (randomly generated) which can be compared with hashed session identificator in database.
Upvotes: 1