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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With