ahwm
ahwm

Reputation: 692

ASP.NET 4.5 persistent cookies not working correctly

We have a web forms project for a client that kept "timing out" and would log the user out periodically while filling out information in the admin area. We ran into something similar on a previous project but were able to work around that easily with this:

if (RememberMe.Checked)
{
    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket((string)r["Login"], true, (90*24*60));
    string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
    cookie.Expires = authTicket.Expiration;
    HttpContext.Current.Response.Cookies.Set(cookie);
    Response.Redirect(FormsAuthentication.GetRedirectUrl((string)r["Login"], false), true);
}
else
{
    FormsAuthentication.SetAuthCookie((string)r["Login"], false);
    FormsAuthentication.RedirectFromLoginPage((string)r["Login"], false);
}

When I tried this same approach on the new project, it had no effect. The only difference I could figure out (after many rewrites and adjustments) was that the new project was using .NET 4.5 and the one where it worked was .NET 4.0. Is this a bug in 4.5 and has anyone else come across this?

We downgraded the new project to 4.0 just to see and so far it appears to be working perfectly without any additional code changes. Most of my searching results in answers that give a code example that looks almost exactly like I'm already doing.

Upvotes: 1

Views: 1149

Answers (1)

ahwm
ahwm

Reputation: 692

In case someone else runs into the same issue, we found the solution here: http://blog.falafel.com/asp-net-forms-authentication-times-out-on-a-shared-host/

Because that application didn’t have it’s own machineKey, it was inheriting the one from the server’s machine.config. This one was configured to auto-generate since it was for a server shared by multiple customers, and it would be a major security flaw if they all shared the same key. Because the key was auto-generating, though, it was also getting regenerated every time the application reset, and failing to decrypt previously handed-out Forms Authentication cookies.

I needed to set a machineKey for my application, so I created a key and put it in a machineKey tag in my application’s web.config, and voila, it worked!

The reason it works on the older site is probably the fact that it has fairly constant traffic and probably isn't idle long enough for the machine key to regenerate. But once we set up a machine key on the new site it worked perfectly: https://blogs.msdn.microsoft.com/amb/2012/07/31/easiest-way-to-generate-machinekey/

Upvotes: 1

Related Questions