Forms Authentication and Shared Domains
I have a number of sites that I’m running on the same domain. I started the Ottawa Events site, and a friend of mine wanted to do a similar thing for Brantford, London, and Woodstock, so I set up a domain for that and have all four of these virtual sites configured in IIS as pointing to the same directory.
A problem I ran into is that the 3 new sites share the same domain name, and the same directory (and thus the same web.config file) but they’re actually 3 different ASP.NET application domains. This is okay – I sniff out in the first Request_Start what the requesting directory is (ie, “/brantford”) and from that look up the configuration for that specific site in the database.
The cookie path that Forms Authentication uses, however, is specified in the web.config file, and isn’t modifiable once set (FormsAuthentication.CookieDomain is a read-only property).
I wanted a different cookie path for each virtual site, so I had to override this. There are two places where this involved changes.
The first is when the user logs in:
protected void Login1_LoggedIn(object sender, EventArgs e)
{
HttpCookie cookie = FormsAuthentication.GetAuthCookie(Login1.UserName,
Login1.RememberMeSet);
string cookiePath = Request.Url.AbsolutePath;
int slashIdx = cookiePath.IndexOf("/", 1);
if (slashIdx != -1)
{
cookiePath = cookiePath.Substring(0, slashIdx);
cookie.Path = cookiePath;
Response.Cookies.Set(cookie);
}
}
This code finds the cookie that Forms Authentication created when the user logged in, and replaces the cookie path with one calculated for this site.
The second change is when the user logs out:
protected void loginStatus_LoggedOut(object sender, EventArgs e)
{
string cookiePath = Request.Url.AbsolutePath;
int slashIdx = cookiePath.IndexOf("/", 1);
if (slashIdx != -1)
{
cookiePath = cookiePath.Substring(0, slashIdx);
HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
cookie.Path = cookiePath;
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
}
}
This ensures that the correct cookie is set to expire when the user logs out.