Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net MVC3 - FormsAuthentication, How to expire cookie when browser closing?

I want to expire cookie that for FormsAuthentication when browser closed. (I want to it works like PHP session does)

Here is my Auth code that located 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 questions is, there are 2 times setting cookie timeout,

in ticket,

DateTime.Now.AddDays(1),

and in authentication in Web.config file

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

how different they are, and which one will effect to actual expire cookie?

Anybody know, please advise me.

Thank you!

like image 766
Expert wanna be Avatar asked May 24 '12 18:05

Expert wanna be


1 Answers

You can't expire the cookie when the browser is closed. You can, however, make the cookie non-persistent, which means it will not save the cookie and thus when you open a new browser it will have a new cookie (be aware, however, that with the way most browsers cache non-persistent cookies with tabs, the entire browser has to be closed for this to clear it out).

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

like image 104
Erik Funkenbusch Avatar answered Sep 29 '22 19:09

Erik Funkenbusch