Home > OS >  How to add a cookie to all subdomain URLs?
How to add a cookie to all subdomain URLs?

Time:02-15

There is an address like x.y.z.com.

I want to set a cookie with the name BREEZESESSION in all the URLs that include .y.z.com. at the end of their URL.

(For Example I want to set BREEZESESSION in x.y.z.com or j.y.z.com or u.y.z.com , any domains with the .y.z.com at their end )

I tried this code but it doesn't work:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);

var cc = new CookieContainer();

cc.Add(new Cookie("BREEZESESSION", "SomeValueHere", "/", "*.y.z.com"));
        
request.CookieContainer = cc;
        
var response = await request.GetResponseAsync();
        
var x = new StreamReader(response.GetResponseStream()).ReadToEnd();

CodePudding user response:

Remove * from the domain:

new Cookie("BREEZESESSION", "SomeValueHere", "/", "y.z.com")

MDN HTTP Cookies documentation states that setting a domain includes the subdomains.

The Domain attribute specifies which hosts can receive a cookie. If unspecified, the attribute defaults to the same host that set the cookie, excluding subdomains. If Domain is specified, then subdomains are always included. Therefore, specifying Domain is less restrictive than omitting it. However, it can be helpful when subdomains need to share information about a user.

For example, if you set Domain=mozilla.org, cookies are available on subdomains like developer.mozilla.org.

  • Related