ASP.NET: How to get FormsAuthenticationTicket object when authentication expired

MegaMatt picture MegaMatt · Dec 20, 2010 · Viewed 13.6k times · Source

I'm trying to check the Expired property of the user's current FormsAuthenticationTicket to see if the authentication period has expired. But when the period has expired, I'm never able to get enough information to even create the ticket to check. I've tried this:

FormsIdentity id = (FormsIdentity)User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;

But User is null when the authentication period has expired. So that won't work. I've tried this:

HttpCookie authCookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

But the Forms Cookie is gone when the authentication period has expired, meaning authCookie will be null. So that doesn't work.

Is there any way to actually get the FormsAuthenticationTicket object when the authentication period has expired? There must be, because there's an "Expired" property in the object. What am I missing?

Thanks.

Answer

Tim Irwin picture Tim Irwin · Jan 7, 2011

Assuming the browser (IE only) does not remove an expired cookie, ASP.Net appears to strip an expired authentication ticket out of the Request.Cookies collection. It is still there in the Request.Header["Cookie"], but not available in the cookies collection. I believe this happens sometime between the "BeginRequest" and "AuthenticateRequest" events. I'm running into the same issue and am exploring it further myself.

    void context_BeginRequest(object sender, EventArgs e)
    {
        string cookie = ((HttpApplication)sender).Context.Request.Cookies[".ASPXFORMSAUTHSS"].Value;
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie);
    }