Create cookie with cross domain - c#

I am working on cookies. I am able to create cookies very easily. To create a cookie I am using this code:
HttpCookie aCookie = new HttpCookie("Cookie name");
aCookie.Value = "Value";
Response.Cookies.Add(aCookie);
This code is fine for me and it gives me localhost as Host. But the problem comes here when I try to add a domain name here like:
HttpCookie aCookie = new HttpCookie("Cookie name");
aCookie.Value = "Value";
aCookie.Domain = "192.168.0.11";
Response.Cookies.Add(aCookie);
Now the cookie is not generated. Any suggestions?

You can only set the domain to yourself (the current site) and sub-domains of yourself, for security reasons. You can't set cookies for arbitrary sites.

As Marc has said - you can't do this; unless the domain is a subdomain of the one returning the response.
The same limitation applies to javascript code on the client adding cookies as well - the same origin policy will apply.
A simple way to achieve this is generally to include on the page returned from abc.com somewhere a reference to a resource on the domain xyz.com - typically a javascript file or something like that.
You have to watch out there, though, because that's a third-party cookie and some users will have those disabled (because it's how ad-tracking works).

Assuming you have a known set of cookies you want to track across domains and that you own all the domains you are sharing cookies with, you can build this functionality yourself. Here is poor man's cross-domain cookie tracking:
You can add "?favoriteColor=red" to all links on abc.com that point to xyz.com.
XYZ Contact
Then do the same thing for all links on xyz.com that point to abc.com.
ABC Contact
Now on every page of abc.com and xyz.com need to check the http request path for ?favoriteColor=red and if it exists, set the favoriteColor cookie on that domain to red.
// Pseudocode
if(queryString["favoriteColor"] != null) {
setCookie("favoriteColor", queryString["favoriteColor"]);
}
Tip 1: Do some validation to ensure that the value you get is valid because users can enter anything.
Tip 2: You should be using https if you're going to do this.
Tip 3: Be sure to url escape your cookie name and value in the url.

Related

How to exclude a site which comes under a specific domain in a cookie c#

We have a set cookie for a domain as .example.com and we have below sites which comes under this domain.
login.example.com
articles.example.com
fitness.example.com
HP.example.com
media.example.com
As, we have set the domain globally and will cover all the sites. But, i dont want to set cookie for the last site i.e. media.example.com
I have tried to set a domain as a site URL but it is not working as all the sites must share the cookies except the last one.
Expected
I don't want a cookie to be shared with media.example.com and shared with the other sites.
To not set cookies for media.example.com I would do it like that:
If you set the cookies in an aspx.cs file:
string sHost = Request.Url.ToString();
if (!sHost.StartsWith("https://media.example.com"))
{
//Write the code to set the cookies
}
If you set the cookies in a class file:
string sHost = HttpContext.Current.Request.Url.ToString();
if (!sHost.StartsWith("https://media.example.com"))
{
//Write the code to set the cookies
}
If you wouldn't use https then replace that with http.
I hope this answers your question.

HttpCookie.Path and mapped urls

According to the official documentation page HttpCookie.Path :
The Path property extends the Domain property to completely describe the specific URL to which the cookie applies. For example, in the URL http:/www.microsoft.com/asp, the domain is www.microsoft.com and the path is /asp.
and then they provide an example: MyCookie.Path = "/asp";
The previous statements in my opinion create more questions than answers.
So my question is what happens if i set the cookie like the previous example and i have a mapped route like /asp/{id}? Will work either?
Also will affect if i define the path without the / just with asp?
And one more question, what's the scope of the previous setting (i mean from what urls i can read the cookie)?
I found the answer on another official page in small letters they write:
The path can either be a physical path under the site root or a virtual root. The effect will be that the cookie is available only to pages in the Application1 folder or virtual root. For example, if your site is called www.contoso.com, the cookie created in the previous example will be available to pages with the path http://www.contoso.com/Application1/ and to any pages beneath that folder. However, the cookie will not be available to pages in other applications such as http://www.contoso.com/Application2/ or just http://www.contoso.com/.
Example:
HttpCookie appCookie = new HttpCookie("AppCookie");
appCookie.Value = "written " + DateTime.Now.ToString();
appCookie.Expires = DateTime.Now.AddDays(1);
appCookie.Path = "/Application1";
Response.Cookies.Add(appCookie);
They also talk about something similar Domain scope:
By default, cookies are associated with a specific domain. For example, if your site is www.contoso.com, the cookies you write are sent to the server when users request any page from that site. (This might not include cookies with a specific path value.) If your site has subdomains—for example, contoso.com, sales.contoso.com, and support.contoso.com—then you can associate cookies with a specific subdomain. To do so, set the cookie's Domain property, as in this example:
Response.Cookies["domain"].Value = DateTime.Now.ToString();
Response.Cookies["domain"].Expires = DateTime.Now.AddDays(1);
Response.Cookies["domain"].Domain = "support.contoso.com";
When the domain is set in this way, the cookie will be available only to pages in the specified subdomain. You can also use the Domain property to create a cookie that can be shared among multiple subdomains, as shown in the following example:
//The cookie will then be available to the primary domain as well as to sales.contoso.com and support.contoso.com domains.
Response.Cookies["domain"].Value = DateTime.Now.ToString();
Response.Cookies["domain"].Expires = DateTime.Now.AddDays(1);
Response.Cookies["domain"].Domain = "contoso.com";
I have change cookie path with following code. Hope it will work for you also.
System.Web.HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId") { Path = "/Application", Value = newID });

HttpWebRequest: Add Cookie to CookieContainer -> ArgumentException (Parametername: cookie.Domain)

I'm trying to login to a website via my application.
What I did:
First I figured out how the browser does the authorization process with Fiddler.
I examined how the POST request is built and I tried to reconstruct it.
The browser sends 4 cookies (Google Analytics) and I tried to set them:
CookieContainer gaCookies = new CookieContainer();
gaCookies.Add(new Cookie("__utma", "#########.###########.##########.##########.##########.#"));
gaCookies.Add(new Cookie("__utmb", "#########.#.##.##########"));
gaCookies.Add(new Cookie("__utmc", "#########"));
gaCookies.Add(new Cookie("__utmz", "#########.##########.#.#.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)"));
(just replaced the original cookie data with #)
Then I went through the code with the debugger and as soon as the first gaCookies.Add is executed, the application stops with an
System.ArgumentException: The parameter '{0}' cannot be an empty string. Parameter name: cookie.Domain
I would like to know why this happens. The constructor of Cookie doesn't require a domain and I don't know where I can get this value?
Would be very great if someone of you could help me with this.
I'm not a webdeveloper or an expert in web stuff so I don't know much about it.
Is there maybe a great source where I can learn about this if there is no "short and quick answer"?
CookieContainers can hold multiple cookies for different websites, therefor a label (the Domain) has to be provided to bind each cookie to each website. The Domain can be set when instantiating the individual cookies like so:
Cookie chocolateChip = new Cookie("CookieName", "CookieValue") { Domain = "DomainName" };
An easy way to grab the domain to is to make a Uri (if you aren't using one already) that contains your target url and set the cookie's domain using the Uri.Host property.
CookieContainer gaCookies = new CookieContainer();
Uri target = new Uri("http://www.google.com/");
gaCookies.Add(new Cookie("__utmc", "#########") { Domain = target.Host });

How do I use the cookie container with RestSharp and ASP.NET sessions?

I'd like to be able to call an authentication action on a controller and if it succeeds, store the authenticated user details in the session.
However, I'm not sure how to keep the requests inside the session as I'm using RestSharp as a detached client. I need to somehow get a key back from the server on successful authorisation and then for each future call, check the key with that stored in the session.
How do I ensure the RestClient in RestSharp sends all future requests with the cookie set correctly so inside service calls, the session variable can be retrieved correctly?
I've been looking at the cookie container with HttpFactory but there doesn't seem to be any documentation on this anywhere.
If someone is having a similar problem, please note that the above is not quite required for a simple "store my cookies after each request" problem.
Jaffas approach above works, but you can simply attach a CookieStore to your RestClient and have the cookies be stored automatically.
I know this is not a solution for everyone, since you might want to store dedicated cookies only. On the other hand it makes your life easier for testing a REST client!
(I used Jaffas variables for ease):
CookieContainer _cookieJar = new CookieContainer();
var client = new RestClient("http://<test-server>/letteron"); //test URL
client.CookieContainer = _cookieJar;
I worked this out in the end.
Basically create a cookie container, then add the session cookie from the response into the cookie container. All future requests will then contain this cookie.
var sessionCookie = response.Cookies.SingleOrDefault(x => x.Name == "ASP.NET_SessionId");
if (sessionCookie != null)
{
_cookieJar.Add(new Cookie(sessionCookie.Name, sessionCookie.Value, sessionCookie.Path, sessionCookie.Domain));
}

Why do some cookies have a '.' before the domain?

Trying to share cookies accross 2 domains in asp.net, for some reason 1 domain has a '.' before the domain, and the other doesn't.
Why is that?
e.g:
.staging.example.com
and
staging.example.com
Is this something to do with how I create the cookie, or a web.config change?
I am not using forms authentication, just creating a cookie manually.
Upd
I am setting the cookie domain like:
HttpCookie c = new HttpCookie("blah");
c.Value = "123";
c.Expires = DateTime.Now.AddHours(12);
c.Domain = ".staging.example.com";
Response.Cookies.Add(c);
For some reason not getting the '.' in the cookie.
What could be the issue?
If you set a . before a domain name, e.g.
.staging.example.com
This means that any domain name that resides under that, will have access to that cookie. E.g. test01.staging.example.com would have access to whatever was in that cookie as if it had created it itself. Without the dot, its limited to the specific domain that is named.
The cookie for .staging.example.com is also readable for each subdomain of that domain, e.g. www.staging.example.com, the other one is not.
To make the cookie available on all subdomains of staging.example.com then you'd set it to .staging.example.com

Categories