keep user logged in when he visit the same page again?

后端 未结 4 1007
余生分开走
余生分开走 2021-02-06 14:47

currently im using session to log in the user. but when i close the browser and open it again i have to log in again. how do you keeo the user logged in in lets say 2 weeks.

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 15:15

    So you want a "Remember me on this computer" option? Here's a language-agnostic way how you can do it:

    1. Create a DB table with at least cookie_id and user_id columns. If necessary also add a cookie_ttl and ip_lock. The column names speaks for itself I guess.
    2. On first-time login (if necessary only with the "Remember me" option checked), generate a long, unique, hard-to-guess key which represents the cookie_id and store this in the DB along with the user_id. Also store this as cookie value of a cookie with a before specified cookie name. E.g. remember. Give the cookie a long lifetime, e.g. one year.
    3. On every request, check if the user is logged in. If not, then check the cookie value cookie_id associated with the cookie name remember. If it is there and it is valid according the DB, then automagically login the user associated with the user_id and postpone the cookie age again.

    As to the security risks, if the key is long and mixed enough (at least 30 mixed chars), then the chances on brute-forcing the login are negligible. Further on you probably already understood what the optional column ip_lock is to be used for. It should represent the IP address of the user. You could eventually add an extra checkbox "Lock login to this IP (only if you have a static IP)" so that the server can use the user's IP address as an extra validation.

    And what if one hijacked the cookie value from an user without an IP lock? Well, there's not much to do against this. Live with it. The "remember me" thing is funny for under each forums and account-hijacks wouldn't hurt that much there, but I would certainly not use it for admin panels and that kind of webpages which controls the server-side stuff.

    It's after all fairly straight forward. Good luck.

提交回复
热议问题