简体   繁体   中英

RememberMe Cookie set expirations time but on Firebug appears as Expiration as Session

I'm using C# and MVC5 to create my own cookie using this code:

// Prepare the ticket
HttpContext.Response.Cookies.Clear();
FormsAuthenticationTicket ticket = 
   new FormsAuthenticationTicket(1, 
                                 "MYNAME", 
                                 DateTime.Now, 
                                 DateTime.Now.AddDays(10), // <<- Expires 10 days 
                                 true, 
                                 null);

// Encrpt the ticket
string encryptedCookie = FormsAuthentication.Encrypt(ticket);

// Create new cookie
HttpCookie cookie = new HttpCookie("MYNAME", encryptedCookie);
cookie.Path = FormsAuthentication.FormsCookiePath;

// Send the Cookie back to the browser
HttpContext.Response.Cookies.Add(cookie);

On the Web.Config I set the name to be

<authentication mode="Forms">
   <forms name="MYNAME" loginUrl="~/Account/Login"></forms>
</authentication>

But when I look the Firebug , the Cookie appears as "MYNAME" but the " expires " is set to Session .
And in fact, when I close the browser, the cookie disappears and when I go back to the site, I always have to login again. The same happens with all other browsers.

What am I doing wrong??

The problem was that I was setting the Expiration at the "Ticket" level but NOT at the "Cookie" level.

Adding

cookie.Expires = ticket.Expiration; 

..solved the issue !!

So the entire code should look like this:

// Prepare the ticket
HttpContext.Response.Cookies.Clear();
FormsAuthenticationTicket ticket = 
   new FormsAuthenticationTicket(1, 
                                 "MYNAME", 
                                 DateTime.Now, 
                                 DateTime.Now.AddDays(10), // <<- Expires 10 days 
                                 true, 
                                 null);

// Encrpt the ticket
string encryptedCookie = FormsAuthentication.Encrypt(ticket);

// Create new cookie
HttpCookie cookie = new HttpCookie("MYNAME", encryptedCookie);
cookie.Path = FormsAuthentication.FormsCookiePath;

// THE MISSING LINE IS THIS ONE
cookie.Espires = ticket.Expiration;   // <<- Uses current Ticket Expiration

// Send the Cookie back to the browser
HttpContext.Response.Cookies.Add(cookie);

How it goes with other browsers? Chrome, IE? If it works fine there, then it should be working on FF as well. If it doesn't work there then possibility is there is issue with code

Take a look on these articles FormsAuthenticationTicket expires too soon

Basic one http://www.codeproject.com/Articles/244904/Cookies-in-ASP-NET http://msdn.microsoft.com/en-us/library/ms178194.ASPX

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM