Sharing ASP.NET cookies across sub-domains

44,616

Solution 1

set the property of Domain to ".mydomain.com" in each Cookies of two subdomains websites

like

Response.Cookies["test"].Value = "some value";
Response.Cookies["test"].Domain = ".mysite.com";

UPDATE 1

in Site

HttpCookie hc = new HttpCookie("strName", "value");
hc.Domain = ".mydomain.com"; // must start with "."
hc.Expires = DateTime.Now.AddMonths(3);
HttpContext.Current.Response.Cookies.Add(hc);

In Site B

HttpContext.Current.Request.Cookies["strName"].Value

Try It

Regards

Solution 2

Add new cookie and specify domain like this

HttpCookie cookie = new HttpCookie("cookiename", "value");
cookie.Domain = "domain.com";

For forms authentication set this in web.config

<forms name=".ASPXAUTH" 
       loginUrl="login.aspx" 
       protection="All" 
       timeout="30" 
       path="/" 
       requireSSL="false" 
       domain="domain.com">
</forms>

The cookie will be accessible to all the subdomains.

In order for each domain to decrypt the the cookie, all web.config files must use the same encryption/decryption algorithm and key. (how to create a machine key)

Example:

// do not wrap these values like this in the web.config
// only wrapping for code visibility on SO
<machineKey  
  validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75
                 D7AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281
                 B"             
  decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719
                 F"
  validation="SHA1"
  decryption="AES"
/>

For easier deployments, these values can be stored in a separate file:

<machineKey configSource="machinekey.config"/>

For added security you can also encrypt the machine key for further protection..

Solution 3

If you're using Forms authentication on all of your sub domains, all you need to do is to add domain=".mydomain.com" property to the <forms> node in your web.config

Note the leading period in .mydomain.com

This simple change by itself will make your authentication cookie valid in all sub-domains; no need to manually set any cookies.

Solution 4

I've created a HttpContext extension method that will write a sub domain safe cookie.

Blog post and discussion

public static class HttpContextBaseExtenstions
{
    public static void SetSubdomainSafeCookie(this HttpContextBase context, string name, string value)
    {
        var domain = String.Empty;

        if (context.Request.IsLocal)
        {
            var domainSegments = context.Request.Url.Host.Split('.');
            domain = "." + String.Join(".", domainSegments.Skip(1));
        }
        else
        {
            domain = context.Request.Url.Host;
        }

        var cookie = new HttpCookie(name, value)
        {
            Domain = domain
        };

        context.Response.SetCookie(cookie);
    }
}

// usage
public class MyController : Controller
{
    public ActionResult Index()
    {
        this.Context.SetSubdomainSafeCookie("id", Guid.NewGuid().ToString());
        return View();
    }
}
Share:
44,616
Jeff Reddy
Author by

Jeff Reddy

First and foremost, I'm a dad. Then I'm a golfer. Since golf doesn't pay the bills, I'm also a developer. Don't get me wrong, I love what I do, it's just that I don't have the time outside of work to develop. Being a dad takes up most of my time at home, and when I have the time, I like to hit the links. I've been developing with Microsoft products since 1999. I started with Visual Basic 5.0, moved onto 6.0 and then .NET in 2003. Since then, I have worked with both VB .NET and C# working on a multitude of windows, web and service applications. Currently, my role has moved beyond developer and as much as I like to sit down and write some code, I find myself managing contractors, services and infrastructure more than coding. I still mentor developers from time to time, most often refactoring code others write that I do writing my own.

Updated on October 23, 2020

Comments

  • Jeff Reddy
    Jeff Reddy over 3 years

    I have two sites, both on the same domain, but with different sub-domains.
    site1.mydomain.com site2.mydomain.com

    Once I'm authenticated on each, I look at the cookies included in subsequent request and they are identical for each site.

    However, if I log into the first site, and then navigate to the other, I expect my cookie from site 1 to be sent with the request to site2, but this is not the case. Here are the properties of my cookies.

    Logging into Site1, this cookie then exists

    Name = MySite 
    Domain = 
    Has Keys = False 
    HttpOnly = False 
    Path = / 
    Value = 1C41854066B03D8CC5679EA92DE1EF427DAC65D1BA0E672899E27C57245C1F0B7E93AB01B5563363AB4815A8F4BDE9D293FD261E03F8E60B8497ABBA964D8D315CCE1C8DD220C7176E21DC361935CF6 
    Expires = 1/1/0001 12:00:00 AM 
    

    Logging into Site2, these cookies then exists.

    Name = MySite 
    Domain = 
    Has Keys = False 
    HttpOnly = False 
    Path = / 
    Value =    C8C69F87F993166C4D044D33F21ED96463D5E4EB41E1D986BF508DA0CBD5C2CA7D782F59F3BC96871108997E899FF7401C0D8615705BDB353B56C7E164D2302EE6731F41705016105AD99F4E0578ECD2 
    Expires = 1/1/0001 12:00:00 AM 
    

    I've set the domain on each (doesn't show up in a request cookie as it's only needed on the client). I've made sure my Forms setting for each are identical I've made sure my machine key settings are the same in both web configs.

    I'm at a loss on why this isn't working. What is it that a cookie contains that the client will send it for one sub-domain and not the other when they are both using the same auth cookies so far as I can tell?

    Please comment if there is more info you'd like to see. I've been struggling with this for two days now. According to this article this should be working.

    UPDATE: code added

    Here is my config file setting for my authentication. This is used in both sites.

    <authentication mode="Forms">
        <forms loginUrl="~/Account/LogOn"
           defaultUrl="~/Home/Index"
           name="MySite" 
           protection="All" 
           path="/" 
           domain="mydomain.com" 
           enableCrossAppRedirects="true" 
           timeout="2880" 
    />
    

    And here is my code to create the cookie in Site1.

    //Add a cookie that the Site2 will use for Authentication
    var cookie = FormsAuthentication.GetAuthCookie(userName, true);
    cookie.Name = "MySite";
    cookie.HttpOnly = false;
    cookie.Expires = DateTime.Now.AddHours(24);
    cookie.Domain = "mydomain.com"; 
    HttpContext.Response.Cookies.Add(cookie);
    HttpContext.Response.Redirect(site2Url,true);
    

    UPDATE 2:

    I noticed something strange while testing. When I add a cookie to the response for site1, it get's added to this directory... C:\Users\jreddy\AppData\Roaming\Microsoft\Windows\Cookies

    When I add a cookie to the response for site, it gets added to this directory... C:\Users\jreddy\AppData\Roaming\Microsoft\Windows\Cookies\Low

    That could be my problem. Could it be that one of my sites is included in the local intranet zone?

    UPDATE 3: Problem found, solution unknown It seems that my problem has to do with my second site being part of the Local Intranet Zone. If I go to Site1 using Firefox it works, but I have to enter my windows credentials. If I go thru IE, my credentials are picked up automatically, but the cookies can't be read by site2. I may ask this in another question.