简体   繁体   中英

Is it a good idea to use a combination of cookies and sessions for keeping users logged in

I am looking at the possibilty to set up a option to keep users logged in. Now I understand a session could be used to allow a user to navigate around without re-entering login information on each page only until the browser is closed and the session is lost. A cookie would be stored client side and has a duration until it expires or the user deletes the cookie.

I was thinking that I could use a combination of both

  1. Create a db table (id,user_id,cookie_token,is_active)
  2. User logs in which creates a row in the db table connecting the user to the cookie_token which is stored on the client browser (system) as well.

    • Each time a token is created, check to see if the user the token is being created for has any active tokens in the system already and set those to inactive before a new one is created.
    • Only one token can be active per user

So every time the user visits the site, the system looks up that token and checks is_active fields, If the user_token is found and is_active = 1 or true, the user data is retrieved (id,name,etc) and this then creates the session and the session variables.

I am not able to find any questions or answers that use a combination of both so it could be that this is just overkill or a very bad idea, I just started to read up on sessions and cookies and have been trying to figure out a system that I could implement myself so would be nice to know if this is good or bad.

I can't reply as a comment anymore, because my reply would be too long... I've implemented something like follows. Unfortunately I can't remember it precisely, but it would give you a pretty good idea:

Visit before manual login:

  • Start a session.
  • At successful login, store a user identification into this session and store a token value into the dB and into the cookie.

Next time the browser visits the page:

  • (re)Start the session.
  • Check if a user identification is set in this session.
    • If so, auto-login the user which matches the identification.
    • If not (session expired due time restriction or browser close), check if a token value is stored in the cookie and if this value matches a token value stored in the dB.
      • If an (unexpired) match found, auto-login the user and remove old tokens.
      • If the user identification is invalid and the token value is invalid/expired:
        • logout the user (which contains all actions to go back to "public" mode like destroying the session, removing tokens, cookies, etc.).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM