Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using cookies to store session in ASP MVC

Storing the entire session in a cookie has been standard in Rails for the last few years - is there an easy way to achieve something similar with ASP MVC?

By default, anything in Session / TempData is stored in memory on the server. In web.config this can be changed to an SQL Store / server-side cache. I'd like to be able to have these objects persisted in a cookie.

It looks like I could implement a custom Session-State Store Provider. Is there a simpler approach?

like image 411
Christopher Stott Avatar asked Oct 30 '09 17:10

Christopher Stott


People also ask

Can cookies store session data?

A session cookie will store all user activity data for a particular browsing session as long as the session is active. Conversely, a persistent cookie will retain your information over a predefined period, regardless of how many times a user logs out of the site or closes the browser.

How are sessions stored in cookies?

The session cookie is a server-specific cookie that cannot be passed to any machine other than the one that generated the cookie. The server creates a “session ID” which is a randomly generated number that temporarily stores the session cookie.

How cookies can be used for session management?

The cookie allows the server to identify the user and retrieve the user session from the session database, so that the user session is maintained. A cookie-based session ends when the user logs off or closes the browser. Cookie-based session management is secure and has performance benefits over alternatives.

Do session variables use cookies in ASP NET MVC?

Session use cookies – Yes : By default Session key is stored in an HTTP non-persistent cookie that the client sends to the server (and server to client) on each request/responses. The server can then read the key from the cookie and re-inflate the server session state.


2 Answers

I think it would be much more efficient to just store the session ID (a hash or whatever) in the cookie, and then use that ID to get the session data from memory / database / whatever storage you prefer. Keeping the full session state in a cookie increases bandwidth innecessarily.

Also, keep security in mind: if the cookie contains authentication information or other sensitive data and you're not careful, it can easily be hacked by the user to gain privileges or otherwise mess with your application (encrypting the data sucks too, because then you have to base-64 encode the encrypted data, which further wastes bandwidth and processing time). You should never trust input from the user.

like image 140
axel_c Avatar answered Sep 23 '22 17:09

axel_c


yes, implement a custom state session-provider. And no, afaik there isn't a simpler approach.

Ps. it isn't as bad as it looks i.e. > half of the odbc sample is writing to the db.

like image 31
eglasius Avatar answered Sep 22 '22 17:09

eglasius