Chad Decker Chad Decker - 1 month ago 8
ASP.NET (C#) Question

Dealing with CORS and Cookie scope across subdomains

I'm having difficulty reconciling some conflicting information from StackOverflow and other sources regarding the use of calls across sub-domains. Consider these two independent sites that share a common domain:


  • site #1:
    www.myDomain.com

  • site #2:
    sub.myDomain.com



Requirements:


  1. Site #1 must be able to execute an AJAX call to site #2 by way of
    sub.myDomain.com/handler.ashx
    .

  2. Site #1 and Site #2 must be able to read each other's cookies.



These requirements lead me to the following questions:


  1. Does the handler code located at sub.myDomain.com/handler.ashx need to alter its response headers to allow CORS? I know that I can write a call like this:

    resp.Headers.Add("Access-Control-Allow-Origin","*");


    …but from what I read, this will expose the handler to all domains. I just want to limit the calls to those originating from
    *.myDomain.com
    . What if I don't include the CORS header at all? What's the default behavior?

  2. Do Site #1 and/or Site #2 need to tweak the Domain property of HttpCookie in order for the two sites to read each other's cookies?

    What if I don't touch the Domain properties at all? What's the default behavior? Some forum responses suggest that cookie scope will be limited to the subdomain, while others suggest the entire domain is in scope (which is what I want) in which case no action would be required on my part.


Answer

The CORS spec is all-or-nothing. It can supports *, null or the exact domain: http://www.w3.org/TR/cors/#access-control-allow-origin-response-header

In your ASHX handler you will need to validate the origin header using the regex, and then you can echo the origin value in the Access-Control-Allow-Origin response header.