Forms Authentication across Sub-Domains

When you authenticate the user, set the authentication cookie's domain to the second-level domain, i.e. parent.com. Each sub-domain will receive the parent domain's cookies on request, so authentication over each is possible since you will have a shared authentication cookie to work with.

Authentication code:

System.Web.HttpCookie authcookie = System.Web.Security.FormsAuthentication.GetAuthCookie(UserName, False);
authcookie.Domain = "parent.com";
HttpResponse.AppendCookie(authcookie);
HttpResponse.Redirect(System.Web.Security.FormsAuthentication.GetRedirectUrl(UserName, 
                                                                       False));

You can set the cookie to be the parent domain at authentication time but you have to explicitly set it, it will default to the full domain that you are on.

Once the auth cookie is correctly set to the parent domain, then all sub-domains should be able to read it.


As a side note, I found that after using jro's method which worked well +1, the FormsAuthenication.SignOut() method didn't work when called from a subdomain other than www/. (I'm guessing because the .Domain property doesn't match) - To get around this I used:

if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
            {
                HttpCookie myCookie = new HttpCookie(FormsAuthentication.FormsCookieName);
                myCookie.Domain = "parent.com";
                myCookie.Expires = DateTime.Now.AddDays(-1d);
                Response.Cookies.Add(myCookie);
            }

In addition to setting a cookie to parent domain also need to make sure that all sites (apps) have same validationKey and decryptionKey () so they all recognise each other's authentication ticket and cookie. Pretty good article here http://www.codeproject.com/KB/aspnet/SingleSignon.aspx


Jro's answer works fine. But make sure to update the webconfig forms authentication setting "domain" , otherwise forms authentication signout will not work properly. Here is the signout issue I came across. Trick here is to have a '.' as the prefix as the domain is set for the cookie as ".parent.com" (use a cookie inspector).

<authentication mode="Forms">          
      <forms cookieless="UseCookies" defaultUrl="~/Default" loginUrl="~/user/signin" domain=".parent.com"  name="FormAuthentication" path="/"/>
    </authentication>