Skip to content

Beware accessing Response.Cookies

September 4, 2012

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
                }
            }
        }
    }
}

The same issue applies to Request.Cookies.

You learn something new every day :)

One Comment leave one →
  1. anon permalink
    April 8, 2013 2:50 pm

    Huh. That’s pretty odd. But wouldn’t you say that reading from Response.Cookies (as opposed to Request.Cookies) represents a practice that should be avoided?

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: