Popular Posts

Thursday, January 5, 2012

Wildcard session cookies

Some browsers use .domain.com as wildcard, others use domain.com
It is common practice for a user to forget the www and most servers will return the same page for www or non-www.
If a user vists the non-www version of a website & the server returns a sessionID cookie, the browser may consider it a wildcard cookie, thus it will use that same cookie for ALL request to ANY subdomain of that site. Normally, each subdomain would have a separate set of cookies, so the server would generate a different sessionId for each.

Here's a method you can call in the Application_EndRequest method of the global.asax.cs to prevent this from happening.

        public static void RemoveWildcardSessionCookies(this HttpApplication application)
        {
            if (System.Web.HttpContext.Current.Request.IsLocal)
                return;

            string host = System.Web.HttpContext.Current.Request.Url.Host;
            int countOfPeriods = host.Count(x => x == '.');

            HttpCookie sessionCookie = application.Request.Cookies["ASP.NET_SessionId"];
            if (sessionCookie != null && countOfPeriods <= 1)
            {
                sessionCookie.Expires = DateTime.Now.AddDays(-1);
                sessionCookie.Value = "";
                if (System.Web.HttpContext.Current.Session != null)
                    System.Web.HttpContext.Current.Session.Abandon();
            }
        }

No comments:

Post a Comment