“Keep Me Logged In” - the best approach

后端 未结 12 1695
Happy的楠姐
Happy的楠姐 2020-11-22 08:30

My web application uses sessions to store information about the user once they\'ve logged in, and to maintain that information as they travel from page to page within the ap

12条回答
  •  一向
    一向 (楼主)
    2020-11-22 08:41

    Security Notice: Basing the cookie off an MD5 hash of deterministic data is a bad idea; it's better to use a random token derived from a CSPRNG. See ircmaxell's answer to this question for a more secure approach.

    Usually I do something like this:

    1. User logs in with 'keep me logged in'
    2. Create session
    3. Create a cookie called SOMETHING containing: md5(salt+username+ip+salt) and a cookie called somethingElse containing id
    4. Store cookie in database
    5. User does stuff and leaves ----
    6. User returns, check for somethingElse cookie, if it exists, get the old hash from the database for that user, check of the contents of cookie SOMETHING match with the hash from the database, which should also match with a newly calculated hash (for the ip) thus: cookieHash==databaseHash==md5(salt+username+ip+salt), if they do, goto 2, if they don't goto 1

    Off course you can use different cookie names etc. also you can change the content of the cookie a bit, just make sure it isn't to easily created. You can for example also create a user_salt when the user is created and also put that in the cookie.

    Also you could use sha1 instead of md5 (or pretty much any algorithm)

提交回复
热议问题