how to setCookie and getCookie using domain name - javascript

when i save cookie, it stored with the current URL link., also when i get cookie that search for the current URL only. i need to save and retrieve cookies with my own defined URL links. can you help me

You cannot read cookies set by different domains. That would be a horrific security problem if it was possible.

Related

Setting document.cookie for another site then redirecting [duplicate]

Say I have a website called a.com, and when a specific page of this site is loaded, say page link, I like to set a cookie for another site called b.com, then redirect the user to b.com.
I mean, on load of a.com/link I want to set a cookie for b.com and redirect user to b.com.
I tested it, and browser actually received the cookie from a.com/link, but it didn't send that cookie on the redirection request to b.com. Is it normal?
Can we set cookies for other domains?
You cannot set cookies for another domain. Allowing this would present an enormous security flaw.
You need to get b.com to set the cookie. If a.com redirect the user to b.com/setcookie.php?c=value
The setcookie script could contain the following to set the cookie and redirect to the correct page on b.com
<?php
setcookie('a', $_GET['c']);
header("Location: b.com/landingpage.php");
?>
Similar to the top answer, but instead of redirecting to the page and back again which will cause a bad user experience you can set an image on domain A.
<img src="http://www.example.com/cookie.php?val=123" style="display:none;">
And then on domain B that is example.com in cookie.php you'll have the following code:
<?php
setcookie('a', $_GET['val']);
?>
Hattip to Subin
Probaly you can use Iframe for this. Facebook probably uses this technique. You can read more on this here. Stackoverflow uses similar technique, but with HTML5 local storage, more on this on their blog
In case you have a.my-company.com and b.my-company.com instead of just a.com and b.com you can issue a cookie for .my-company.com domain - it will be accepted and sent to both of the domains.
You can't, at least not directly. That would be a nasty security risk.
While you can specify a Domain attribute, the specification says "The user agent will reject cookies unless the Domain attribute specifies a scope for the cookie that would include the origin server."
Since the origin server is a.com and that does not include b.com, it can't be set.
You would need to get b.com to set the cookie instead. You could do this via (for example) HTTP redirects to b.com and back.
Setting cookies for another domain is not possible.
If you want to pass data to another domain, you can encode this into the url.
a.com -> b.com/redirect?info=some+info (and set cookie) -> b.com/other+page
see RFC6265:
The user agent will reject cookies unless the Domain attribute
specifies a scope for the cookie that would include the origin
server. For example, the user agent will accept a cookie with a
Domain attribute of "example.com" or of "foo.example.com" from
foo.example.com, but the user agent will not accept a cookie with a
Domain attribute of "bar.example.com" or of "baz.foo.example.com".
NOTE: For security reasons, many user agents are configured to reject
Domain attributes that correspond to "public suffixes". For example,
some user agents will reject Domain attributes of "com" or "co.uk".
(See Section 5.3 for more information.)
But the above mentioned workaround with image/iframe works, though it's not recommended due to its insecurity.
You can't, but... If you own both pages then...
1) You can send the data via query params (http://siteB.com/?key=value)
2) You can create an iframe of Site B inside site A and you can send post messages from one place to the other. As Site B is the owner of site B cookies it will be able to set whatever value you need by processing the correct post message. (You should prevent other unwanted senders to send messages to you! that is up to you and the mechanism you decide to use to prevent that from happening)
Send a POST request from A. Post requests are on the serverside only and can't be accessed by the client.
You can send a POST request from a.com to b.com using CURL (recommended, serverside) or a hidden method="POST" form (clientside). If you go for the latter, you might want to obfuscate your JavaScript so that the user won't be able to understand the algorithm and interfere with it.
Make a gateway on b.com to set cookies:
<?php
if (isset($_POST['data']) {
setcookie('a', $_POST['data']);
header("Location: b.com/landingpage");
}
?>
If you want to bring security a step further, implement a function on both sides (a.com and b.com) to encrypt (on a.com) and decrypt (on b.com) data using a cryptographic cypher.
If you're trying to do something that must be absolutely secure (e.g. transfer a login session) try oAuth or take some inspiration from https://api.cloudianos.com/docs#v2/auth
Here is what I've used. Note, this cookie is passed in the open (http) and is therefore insecure. I don't use it for anything which requires security.
Site A generates a token and passes as a URL parameter to site B.
Site B takes the token and sets it as a session cookie.
You could probably add encryption/signatures to make this secure. Do your research on how to do that correctly.
In this link, we will find the solution Link.
setcookie("TestCookie", "", time() - 3600, "/~rasmus/", "b.com", 1);

Subdomain read and delete primary domain cookie

I need to set a cookie from my main domain, read then remove the cookie from a subdomain. But I also need to possibly set that cookie again on the domain in the future, and read it later on the subdomain. Basically, a stream of one-way communication. I cannot have the main domain handle unsetting the cookie, because it could be months between users hitting the main domain and the subdomain.
I set a cookie on my domain, like so:
document.cookie = "mycookie=testcookie;domain=example.com;max-age=31536000;";
I access it just fine on another subdomain, as such:
document.cookie.replace(/(?:(?:^|.*;\s*)testcookie\s*\=\s*([^;]*).*$)|^.*$/, "$1");
I then try to kill it from the subdomain:
document.cookie = "mycookie=;domain=example.com;max-age=0;";
That does not work. Cookie is still set.
However, setting it like this clears it:
document.cookie = "mycookie=;domain=example.com;max-age=31536000;";
It now returns "" when asking for it from the subdomain.
But... if I go back to the domain and set it again, and I can see it has been set, the subdomain still returns ""
Is there some sort of... hierarchy of cookies I'm missing? I'm unsure how this behaves or how to overcome this.
In order to enable this you have to place a period . before the root domain, like so: .example.com This is important because of the way the cookie standardization is setup. This format should be compatible with most modern browsers.
In addition, the path must be identical when accessing or modifying the cookie across different subdomains. The easiest way to do this is to just use the root path for the domain, /. For example, if you set the cookie from sub1.example.com/page1 and try to access it from sub2.example.com/page2, even though you set the domain as .example.com you also have to set the path=/ in order to access it and modify it from any path on other subdomains.
Ultimately:
document.cookie = "mycookie=testcookie;domain=.example.com;path=/;max-age=31536000";
will enable you to set it and
document.cookie = "mycookie=;domain=.example.com;path=/;max-age=0";
will let you delete it.

View cookies using JavaScript [duplicate]

I can't access any cookie from JavaScript. I need to read some value and send them via JSON for my custom checks.
I've tried to access cookies from JS, like it was described at:
http://www.w3schools.com/js/js_cookies.asp
Get cookie by name
As you can see at the code, it's seen as clear as a crystal the next:
var c_value = document.cookie;
When I'm trying to access the document.cookie value from the Chrome's web-debugger, I see only the empty string at the Watch expressions:
So I can't read cookies value, which I need.
I've checked the cookie name, which I'm sending to get an associated value IS correct.
Also, I'm using the W3Schools source code for getting cookies, if you're interested (but from the 2nd link, the technique is similar).
How can I fix my issue?
You are most likely dealing with httponly cookies. httponly is a flag you can set on cookies meaning they can not be accessed by JavaScript. This is to prevent malicious scripts stealing cookies with sensitive data or even entire sessions.
So you either have to disable the httponly flag or you need to find another way to get the data to your javascript.
By looking at your code it should be easy to disable the http only flag:
Response.AddHeader("Set-Cookie", "CookieName=CookieValue; path=/;");
Response.SetCookie(new HttpCookie("session-id") { Value = Guid.NewGuid().ToString(), HttpOnly = false });
Response.SetCookie(new HttpCookie("user-name") { Value = data.Login, HttpOnly = false });
Now you should be able to access the cookie information from JavaScript. However I don't know exactly what kind of data you are trying to get so maybe you can go for another approach instead and for example render some data attribute on the page with the information you need instead of trying to read the cookie:
<div id="example" data-info="whatever data you are trying to retrieve"></div>
console.log(document.getElementById('example').getAttribute('data-info'));
keep an eye also to the cookie's Path attribute, as the cookie is only visible to subdirectories under Path. I had your issue and I solved setting Path "/"
I would say http only is your first culprit but this can also occur by not setting the scope of your cookie.
If the site has been redirected from another domain, you will need to look into setting the scope of the cookie. Domain and Path defines the scope of the cookie, which URLs the cookie should be sent to. Depending on this, you might not see the cookie in your response.
I ran across this issue when setting a cookie on a successful SAML SSO login and couldn't retrieve the cookie from the Document because it was never send as part of the request.
I had the same problem several times. And every time, it was for a different reason.
Different reasons:
problem of httpOnly field. It was set to false and I was trying to access it from the console. Setting it to true or accessing it from the source code did the trick.
problem of secure field. It was true and I was using only http.
problem of Expires / Max-Age. The cookie was outdated and it was not visible in document.cookie.
If your cookie is set as Set-Cookie or Set-Cookie2 it's not part of the response headers collection: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders%28%29-method
Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2.
If you are using some secure authentication then that case you could not access cookies directly because of secure. you have to change some response attribute in server side using below code .
Response.AddHeader("Set-Cookie", "CookieName=CookieValue; path=/;");
Response.SetCookie(new HttpCookie("session-id") { Value = Guid.NewGuid().ToString(), HttpOnly = false });
Response.SetCookie(new HttpCookie("user-name") { Value = data.Login, HttpOnly = false });
But you should not because it may change secure to un-secure, so you have to find out solution that be done in server side to delete cookies and allow to you do some operations.
Its possible to do changes in server side.

Retrieving all subdomaines/superdomains cookies from with subdomain using javascript

I am getting partial list of cookies with document.cookie when executing on subdomain. I would like to retrieve superdomain+subdomain cookies. Is there any way to do that?
Let say I have a domain
example.com
sub.example.com
And I have cookies set
name=value domain
c1=2 => .example.com
c2=4 => sub.example.com
If url in browser is sub.example.com I want to get all the above cookies how would I do that? document.cookie only returns c2=4
You are trying to access cookies from different domain. Browser not going to allow this. Please refer this.
Turns out there was a flag in browser which sets httponly cookie, This cookie is not visible from document.cookie javascript method for security reasons.

How to set a cookie for another domain

Say I have a website called a.com, and when a specific page of this site is loaded, say page link, I like to set a cookie for another site called b.com, then redirect the user to b.com.
I mean, on load of a.com/link I want to set a cookie for b.com and redirect user to b.com.
I tested it, and browser actually received the cookie from a.com/link, but it didn't send that cookie on the redirection request to b.com. Is it normal?
Can we set cookies for other domains?
You cannot set cookies for another domain. Allowing this would present an enormous security flaw.
You need to get b.com to set the cookie. If a.com redirect the user to b.com/setcookie.php?c=value
The setcookie script could contain the following to set the cookie and redirect to the correct page on b.com
<?php
setcookie('a', $_GET['c']);
header("Location: b.com/landingpage.php");
?>
Similar to the top answer, but instead of redirecting to the page and back again which will cause a bad user experience you can set an image on domain A.
<img src="http://www.example.com/cookie.php?val=123" style="display:none;">
And then on domain B that is example.com in cookie.php you'll have the following code:
<?php
setcookie('a', $_GET['val']);
?>
Hattip to Subin
Probaly you can use Iframe for this. Facebook probably uses this technique. You can read more on this here. Stackoverflow uses similar technique, but with HTML5 local storage, more on this on their blog
In case you have a.my-company.com and b.my-company.com instead of just a.com and b.com you can issue a cookie for .my-company.com domain - it will be accepted and sent to both of the domains.
You can't, at least not directly. That would be a nasty security risk.
While you can specify a Domain attribute, the specification says "The user agent will reject cookies unless the Domain attribute specifies a scope for the cookie that would include the origin server."
Since the origin server is a.com and that does not include b.com, it can't be set.
You would need to get b.com to set the cookie instead. You could do this via (for example) HTTP redirects to b.com and back.
Setting cookies for another domain is not possible.
If you want to pass data to another domain, you can encode this into the url.
a.com -> b.com/redirect?info=some+info (and set cookie) -> b.com/other+page
see RFC6265:
The user agent will reject cookies unless the Domain attribute
specifies a scope for the cookie that would include the origin
server. For example, the user agent will accept a cookie with a
Domain attribute of "example.com" or of "foo.example.com" from
foo.example.com, but the user agent will not accept a cookie with a
Domain attribute of "bar.example.com" or of "baz.foo.example.com".
NOTE: For security reasons, many user agents are configured to reject
Domain attributes that correspond to "public suffixes". For example,
some user agents will reject Domain attributes of "com" or "co.uk".
(See Section 5.3 for more information.)
But the above mentioned workaround with image/iframe works, though it's not recommended due to its insecurity.
You can't, but... If you own both pages then...
1) You can send the data via query params (http://siteB.com/?key=value)
2) You can create an iframe of Site B inside site A and you can send post messages from one place to the other. As Site B is the owner of site B cookies it will be able to set whatever value you need by processing the correct post message. (You should prevent other unwanted senders to send messages to you! that is up to you and the mechanism you decide to use to prevent that from happening)
Send a POST request from A. Post requests are on the serverside only and can't be accessed by the client.
You can send a POST request from a.com to b.com using CURL (recommended, serverside) or a hidden method="POST" form (clientside). If you go for the latter, you might want to obfuscate your JavaScript so that the user won't be able to understand the algorithm and interfere with it.
Make a gateway on b.com to set cookies:
<?php
if (isset($_POST['data']) {
setcookie('a', $_POST['data']);
header("Location: b.com/landingpage");
}
?>
If you want to bring security a step further, implement a function on both sides (a.com and b.com) to encrypt (on a.com) and decrypt (on b.com) data using a cryptographic cypher.
If you're trying to do something that must be absolutely secure (e.g. transfer a login session) try oAuth or take some inspiration from https://api.cloudianos.com/docs#v2/auth
Here is what I've used. Note, this cookie is passed in the open (http) and is therefore insecure. I don't use it for anything which requires security.
Site A generates a token and passes as a URL parameter to site B.
Site B takes the token and sets it as a session cookie.
You could probably add encryption/signatures to make this secure. Do your research on how to do that correctly.
In this link, we will find the solution Link.
setcookie("TestCookie", "", time() - 3600, "/~rasmus/", "b.com", 1);

Categories

Resources