Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store an object in a cookie?

While this is possible in C#: (User is a L2S class in this instance)

User user = // function to get user
Session["User"] = user;

why this is not possible?

User user = // function to get user
HttpCookie cookie = new HttpCookie();
cookie.Value = user; 

and how can it be done? I don't want to store the id of the user within the cookie and then do some validation.

Btw, if possible, is it secure to store an object within a cookie rather than only the ID ?

like image 820
Shaokan Avatar asked Jul 07 '11 22:07

Shaokan


People also ask

Can you store objects in cookie?

Store objects in the CookiesThe cookies store information in the string format only. If users want to store any other types of data in the cookies, they need to convert it to the string using the stringify() method. In this section, we will convert the object to a string and store it in cookies.

How do you store things in cookies?

Store cookies in layers The last thing you want is for your cookies to stick together! To prevent sticking when you store your cookies, arrange them in a single layer and add a piece of parchment paper or waxed paper between layers. (Here's why you should bake cookies on parchment paper, too!)

Can we store JSON in cookies?

The idea is to keep a JavaScript object (a hash array) of all little variable things you want to store in a cookie. Then, once ready, you encode the object into a JSON string and save it to a cookie. To load the data from a previously saved cookie, you decode the JSON string back into an object.

Can I store array in cookie?

Cookies can only store string values. You cannot store an array directly into a cookie.


2 Answers

A cookie is just string data; the only way to do that would be to serialize it as a string (xml, json, base-64 of arbitrary binary, whatever), however, you shouldn't really trust anything in a cookie if it relates to security information ("who am I?") as a: it is easy for the end-user to change it, and b: you don't want the overhead of anything biggish on every single request.

IMO, caching this as the server is the correct thing; don't put this in a cookie.

like image 128
Marc Gravell Avatar answered Oct 12 '22 13:10

Marc Gravell


You can use JSON

string myObjectJson = new JavaScriptSerializer().Serialize(myObject);
var cookie = new HttpCookie("myObjectKey", myObjectJson) 
{     
    Expires = DateTime.Now.AddYears(1) 
};
HttpContext.Response.Cookies.Add(cookie);
like image 43
Erik Bergstedt Avatar answered Oct 12 '22 14:10

Erik Bergstedt