ssn771
ssn771

Reputation: 1270

ASP.NET MVC user data in forms authentication cookie versus adding to session

I think I have a simple question regarding authentication in asp.net mvc 4. One thing that isn't clear to me is I can add/serialize user data into the authorization cookie. What are the benefits/trade offs of putting the user data in the authentication cookie versus adding the user data to the session? Do I even need to put anything unique to the user in the authentication cookie? Should I serialize all of the user data and put that in the cookie and not use the session to store the user data?

My application is very simple and does not have any roles. I just want to make sure it would scale well if necessary.

For now, I just put the users email in the authentication cookie and add the user object to the session. I'm using the following code to authorize a user:

FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
      1,
      user.Email,
      DateTime.Now,
      DateTime.Now.AddMinutes(15),
      false,
      user.Email); // adding the user email in the authTicket
string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
Session["User"] = user; //adding user data to session
Response.Cookies.Add(faCookie);

return RedirectToAction("Summary", "Account");

I really appreciate any insight. Thanks!

Upvotes: 7

Views: 6740

Answers (2)

John Heilman
John Heilman

Reputation: 101

Another thing to consider is using Profile. Gettable at HttpContext.Profile view http://msdn.microsoft.com/en-us/library/ewfkf772%28v=vs.100%29.aspx

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

The problem with the ASP.NET session is that by default it is stored in-memory. This means that if you are running in a web farm you will need to use an out-of-process persistence for your session, otherwise not all nodes across your webfarm will have the same information. So you will need to persist your sessions in SQL server which is far more expensive than simply reading the user data from the forms authentication cookie.

Another important aspect about ASP.NET Session is that if you ever decide to use it (personally I never use it), you will have to ensure that its timeout is the same as your forms authentication cookie timeout otherwise your cookie might expire but the user data still present in the session or worse, the session might expire but the forms authentication cookie be still valid.

So at the end of the day, you will have to be solving far more complex problems if you ever decide to use ASP.NET Session than you initially had (which was to simply persist some user information on all requests).

Upvotes: 11

Related Questions