Why is my ASP.NET MVC persistent auth cookie not working?

I’m using ASP.NET MVC 3, with forms authentication (based on modified vanilla account code you get with file->new).

When you login, I am setting an auth cookie with

FormsAuthentication.SetAuthCookie(userName, true);

So this should set a persistent cookie. But if I close the browser and re-open, when I browse to the site I am forced to log in again! I can see using chrome dev tools that the cookie (.ASPXAUTH) is being created and not being deleted when I close the browser, so what’s happening?

My web.config:

<authentication mode="Forms">
  <forms loginUrl="~/Account/LogIn" timeout="10000"/>
</authentication>

I’m testing this locally, under IIS if that makes any difference.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I’d better create myself a cookie using authentication ticket.
SetAuthCookie creates an auth ticket under the hood. Have you tried making your own auth ticket? It will let you store extra data on it.

Here’s an example :

// create encryption cookie         
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, 
        userName, 
        DateTime.Now,
        DateTime.Now.AddDays(90),
        createPersistentCookie, 
        string.Empty);

// add cookie to response stream         
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);    
System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
if (authTicket.IsPersistent) 
{     
      authCookie.Expires = authTicket.Expiration; 
}
System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);

Hope this helps.

Method 2

Solved from comment from @alexl:

you can check this answer: Making user login persistant with ASP .Net Membership

Ok, this link seemed to sort it for me – sticking with SetAuthCookie and tweaking my config to explicitly set the cookie name (in the web.confg), and all is working now. Weird! –


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x