Asp.Net MVC3 - FormsAuthentication, How to expire

2019-06-17 02:38发布

问题:

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!

回答1:

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.



回答2:

jQuery unload event can be used to detect the browser closing.

But this event is also fired when : The user clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event.Even a page reload will first create an unload event.

Bind an event handler to the "unload" JavaScript event.

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