Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC Cookies Best Practices

I'm looking for some guidance with respect to cookies in ASP.Net MVC (or just cookie handling in general). I have been storing authentication information about users who authenticate via a form login in a cookie. This is working great, but I now need to store a little more information in the cookie. This additional information is not really "authentication related" so I'm hesitant to store it in the authentication ticket. Is there a better practice for storing extra information. Is it possible to set multiple cookies (and if so is that a good/bad practice)? Other things I should be considering here?

Here is the current code I'm using to set the authentication ticket and wrap it in a cookie:

private HttpCookie GetAuthCookie(AuthToken authToken)
{
    var authTokenXml = serializationService.Serialize(authToken);
    var authCookieString = FormsAuthentication.Encrypt(
        new FormsAuthenticationTicket(
            0,
            Keys.AuthToken,
            DateTime.Now,
            DateTime.Now.AddMinutes(AppSettings.SessionTimeoutMinutes),
            true,
            authTokenXml));
    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, authCookieString)
                     {
                         Expires = DateTime.Now.AddDays(AppSettings.AuthCookieExpireDays)
                     };
    return cookie;
}
like image 760
Paul Avatar asked Jul 27 '10 20:07

Paul


People also ask

How cookies works in ASP NET MVC?

In ASP.Net MVC application, a Cookie is created by sending the Cookie to Browser through Response collection (Response. Cookies) while the Cookie is accessed (read) from the Browser using the Request collection (Request. Cookies).

Which of the following is the best practice when dealing with cookies?

A best-practice for cookies is to minimize their use. For instance, limit your cookie usage to just remembering the session id, and then store your data on the server side. In the EU, cookies are subject to legal regulations, and using cookies for almost anything but session ids require explicit client consent.


1 Answers

Rule of thumb: store in the cookie only the minimum (usually this is the user id) and use this minimum to fetch the rest from your datastore every time you need it. If you are happy with the performance you can stop reading.

If you realize that there are too many queries to your datastore you could use session or cache the results of your queries.

like image 160
Darin Dimitrov Avatar answered Sep 28 '22 10:09

Darin Dimitrov