Asp.Net MVC3 - FormsAuthentication, How do I expire a cookie when closing a browser?

I want to end the cookie for FormsAuthentication when the browser is closed. (I want it to work, how the PHP session works)

Here is my Auth code which is in Model (Not controller).

Models / Auth.cs

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, model.UserId, DateTime.Now, DateTime.Now.AddDays(1), true, model.UserId +" "+reader["lastname"], FormsAuthentication.FormsCookiePath); string hash = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); if (ticket.IsPersistent) { cookie.Expires = ticket.Expiration; } HttpContext.Current.Response.Cookies.Add(cookie); 

Web.config

 <authentication mode="Forms"> <forms name="user" timeout="60" loginUrl="~/Auth/login" path="/"></forms> </authentication> <authorization> <deny users="?" /> </authorization> 

And one more question: is there a 2 time set cookie timeout,

on the ticket

 DateTime.Now.AddDays(1), 

and during authentication in the Web.config file

 <forms name="user" timeout="60" loginUrl="~/Auth/login" path="/"></forms> 

how different are they, and which one will affect the actual expire cookie?

Does anyone know please let me know.

Thanks!

+7
source share
2 answers

Cookies cannot expire when the browser is closed. However, you can make the cookie inconsistent, which means that it will not save the cookie, and thus open a new browser, it will have a new cookie (remember, however, since most browsers cache inconsistent cookies with tabs, the entire browser must be closed for this to clear it).

As for your second question, the web.config entry is used if you do not specify a timeout.

+9
source

The jQuery unload event can be used to detect browser closure.

But this event also fires when: The user clicked a link to leave the page, or typed a new URL in the address bar. The forward and backward buttons trigger an event. Even reloading the page first creates an unload event.

Bind the event handler to the unload JavaScript event.

Answer your second question, the timeout that you set in your code, overriding the web.config entry.

0
source

All Articles