Petr
Petr

Reputation: 183

MVC3 Doesn't accept cookie

I just launched my first MVC3 application and everything works fine except cookies authorisation. When a user visits my site and logs in I set a .ASPAUTH cookie with data about that user. It works well untill some time passes. Then I have to log in again even though the cookie is in the browser and I can see that expiration is set to one year later. It works fine on my localhost. It seems to me that it instead of setting my info into cookie it is somehow in session, but even if I restart my computer within an hour I am still logged in. But if I don't visit the web in 1 hour, after that I am logged out.

Thanks for any help.

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1,
                requestedUser.Name,
                DateTime.Now,
                DateTime.Now.AddYears(1),
                true,
                string.Format("{0};{1};{2}", requestedUser.IDUser.ToString(), requestedUser.IsAdmin.ToString(), profilePicture));

            string encryptedTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            cookie.Expires = keepLogged == "keepLogged" ? DateTime.Now.AddYears(1) : DateTime.Now.AddHours(1);

            this.Response.Cookies.Add(cookie);
            return RedirectToAction("Index", "Posts");

Upvotes: 3

Views: 390

Answers (1)

MikeSW
MikeSW

Reputation: 16348

You need to set the machinekey in web.config something like this

 <machineKey validationKey="4B79DF965DC586D2B267BDECB4580D40EE6811EE171AC65D929BECD8865C09ED8681B92F2177FE9F72B8E822B26914C79C1FF590CCEE65469CBC6FACD7D9F203" decryptionKey="CF39BCCD33BC38D17A704DFEB85AD9C5F265669FCD6AB54C" validation="SHA1" />

You can use this http://aspnetresources.com/tools/machineKey tool to do it, but you have to paste it intro web.config.

Everytime the app pool recycels the app is restarted and if it's not set in web.config, a new machinekey is automatically generated. The FormsAuthentication cookie is hashed with that machine key and every time it changes, the cookie becomes invalid

Upvotes: 6

Related Questions