简体   繁体   中英

How do I link a data saved in cookie to a user?

When logged in with specific user (ie user 1), I can save my data in form of cookie with following code snippet:

import Cookies from 'universal-cookie';

const cookie = new Cookies()
cookie.set('cookie','user1value', { path:'/'})

But when I login with user 2, I don't want my user 2 to be able to access the cookie that was saved while I was logged in from user 1 ie I don't want my user 2 be able to see user1value cookie given in the code above. The given code allows all the user to access the cookie while being on the same site. Is there a way to map a certain user to specific cookie value? If so, can someone give me a general idea how I can achieve that?

Typically you don't want to store user related info in the cookies after user logs out. You can get user related info after user logges in again, and set it as cookie. Some options that I can think of:

  1. As said in the comments, by using same cookie name, you can overwrite the previous cookie in user's browser. That way, old cookie value will be lost.

  2. On logout, you can set cookie value to empty string(or any other unused value) and set "expires" value as described in this post .

  3. If you don't want your user info to be readable in cookie value, you can use a session id as cookie value. Then, in a data storage in server side, you can relate this session id with the logged in user info. Once user logs out, you can delete the session in database as well as the cookie.

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