“Keep Me Logged In” - the best approach

后端 未结 12 1564
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 09:04

    My solution is like this. It's not 100% bulletproof but I think it will save you for the most of the cases.

    When user logged in successfully create a string with this information:

    $data = (SALT + ":" + hash(User Agent) + ":" + username 
                         + ":" + LoginTimestamp + ":"+ SALT)
    

    Encrypt $data, set type to HttpOnly and set cookie.

    When user come back to your site, Make this steps:

    1. Get cookie data. Remove dangerous characters inside cookie. Explode it with : character.
    2. Check validity. If cookie is older than X days then redirect user to login page.
    3. If cookie is not old; Get latest password change time from database. If password is changed after user's last login redirect user to login page.
    4. If pass wasn't changed recently; Get user's current browser agent. Check whether (currentUserAgentHash == cookieUserAgentHash). IF agents are same go to next step, else redirect to login page.
    5. If all steps passed successfully authorize username.

    If user signouts, remove this cookie. Create new cookie if user re-logins.

提交回复
热议问题