I am using ASP.NET MVC and want to be able to automatically log somebody in when they return to the site (in exactly same way that this site does).
When a user first registers or logs in I set the cookie as follows:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
"playerid",
DateTime.Now,
DateTime.Now.AddMinutes(1), //This will be set to a longer period in live...
true,
Username + "|" + item.PlayerID.ToString(),
FormsAuthentication.FormsCookiePath);
string encTicket = FormsAuthentication.Encrypt(ticket);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
If I test this by logging in as a user and then look at the Cookies
tab in Firebug
then the expiration is set to Session
. If I close the browser and then go back to my site I am no longer logged in. This is what I'd expect as the session ends when the browser is closed (but it is not what I want to happen!).
However, if I log in and navigate about the site, then after a minute elapses the expiry no longer shows as Session
but appears as an actual date stamp. If I then close the browser and go back to my site I am auto logged in.
In summary, it seems as if my expiration is set to Session
until the actual expiry date I have stipulated passes (t + 1 min in this case) and I have been active on the site (I am using sliding expiration).
Any ideas how I can have my expiration set to what I am stating in the FormsAuthentication ticket (and not show as Session
)?
You should create a persistent cookie
that is stored on the client harddrive by setting the Expires
property:
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
{
// setting the Expires property to the same value in the future
// as the forms authentication ticket validity
Expires = ticket.Expiration
};
Response.Cookies.Add(cookie);
Make sure that you have specified the same expiration timeout for the cookie and the forms authentication ticket. Now when you look with FireBug you will see that the when the cookie is emitted the Expires
property is being set in the future which will make the cookie persistent and survive browser restarts:
Set-Cookie: ASPXAUTH=...; Expires=Tue, 15-Jan-2014 21:47:38 GMT; Path=/; HttpOnly