ASP.NET: Beware accessing Response.Cookies

I learned something new about ASP.NET today that I had never come across before. I was writing code that looked something like this:

private void CheckForFormsLogout(HttpContext ctx)
{
    if (ctx.User.Identity.IsAuthenticated)
    {
        var logoutCookie = ctx.Response.Cookies[FormsAuthentication.FormsCookieName];
        if (logoutCookie != null)
        {
            var now = DateTime.UtcNow;
            if (DateTime.MinValue < logoutCookie.Expires && logoutCookie.Expires < now)
            {
                // yes, user is logging out
            }
        }
    }
}

Turns out this code has a serious flaw that is actually triggering the logout. The issue is how I was checking for the cookie on the Response.Cookies collection. Turns out that the CookieCollection class creates a cookie if the one you’re asking for doesn’t exist. So in my attempt to see if the cookie was present, I was creating it. The newly created cookie was empty and thus had the side effect of replacing the valid forms authentication cookie with an empty value.

Here’s the change I made to correct the problem:

private void CheckForFormsLogout(HttpContext ctx)
{
    if (ctx.User.Identity.IsAuthenticated)
    {
        if (ctx.Response.Cookies.AllKeys.Contains(FormsAuthentication.FormsCookieName))
        {
            var logoutCookie = ctx.Response.Cookies.Get(FormsAuthentication.FormsCookieName);
            if (logoutCookie != null)
            {
                var now = DateTime.UtcNow;
                if (DateTime.MinValue < logoutCookie.Expires && logoutCookie.Expires < now)
                {
                    // yes the user is logging out
                }
            }
        }
    }
}

You learn something new every day.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s