Setting and Access Cookies from Main Domain to Sub-Domain - javascript

I got a peculiar situation and spent lots of time in investigating but could not success.
I have a domain like www.A where on home page I'm running a Javascript to access a PHP script from another subdomain dev.A. This PHP script needs to set a cookie and then I want to access same cookie in another script which I'm accessing again under www.A.
Kindly help in achieving this.
Regards
Mohtashim

If you want to set the cookie in a domain and make sure it's available on every sub-domain you should use the domain (without the www subdomain) in the setcookie function:
setcookie('cookie_name', 'cookie_value' , 0 , "" , 'yourdomain.com');
// ^ This is the expiring time of the cookie
// ^ This is the path of the cookie
This will allow your subdmains (both www.A and dev.A) to access that cookie.
Read more here about all the parameters of the setcookie function.

Finally I got a solution where I needed to fix my Ajax call to add the following:
crossDomain: true,
xhrFields: {
withCredentials: true
},
But then it started giving me issue related to Access-Control-Allow-Origin because in my httpd.conf it was set to *, so I commented that out but still it did not resolve the issue, then I added following two lines in my PHP scripts which were setting session and reading sessions:
header("Access-Control-Allow-Origin: https://www.example.com");
header("Access-Control-Allow-Credentials : true");
Finally, after spending whole night now I'm able to use my session in a sub-domain. Hope this will help someone.

Related

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.

Cookies are not set under chrome dev-tools>Application>Cookies?

Here is a screenshot of the application :
1: We can see Set Cookie here
2: We can see Cookie under response here
3: Doesn't appear here
Tried to find a lot of resources read things about CORS as well but still haven't been able to solve this issue.
Update :
After much discussions with my colleagues this issue couldn't be resolved, thus we have decided to change the code structure and the working of the application to go around this issue.
What you need to do is the endpoint http://4bf9e0a0.ngrok.io/ that generates the token cookie needs to write the cookie on your behalf for your domain http://samldemo.builtapp.io.
Ok in your saml auth service/ method on ngrok.io , when you write the cookie, set the domain similar to this:
setCookie('authtoken', 'bltd435345353453', {
domain: 'samldemo.builtapp.io', // The domain you to read the cookie on
...
...
...
});
Some Auth/Token providers will provide an API to configure how the the token created and configured, for example setting up your domain, etc. This is only possible server side.

PhantomJS not accepting Cross Domain Cookies

Hey guys i am using PhantomJS (1.10.0) and Node-phantom-simple (https://github.com/baudehlo/node-phantom-simple) in order to control phantom through a node script. There seems to be an issue when trying to add/set cookies in phantom for a domain other than the one phantom is currently on. It seems that phantom simple ignores the cross domain cookies and doesnt add them. Has anyone else experience this problem/ have any ideas of how to fix it?
Cookie To Add
"test_cookie=CheckForPermission; path=/; domain=.doubleclick.net;"
What I Have Tried:
I first tried using phantoms add and set cookie methods to add the cross domain cookie but phantom did not add the cookie. I then tried using the injectJs method to inject a javascript file with the bellow contents
document.cookie = "test_cookie=CheckForPermission; path=/; domain=.doubleclick.net;";
but phantom still did not add the cookie to its cookie jar. However if i remove the domain part of the above statement the cookie is added with domain equal to phantoms current domain. How can i fix this and have the domain be set to ".doubleclick.net"

why is jquery.cookie.js not returning the cookie?

so I have been using this plugin for working with cookies for a bit and for some reason when i set a cookie it shows up in my browser's cookies list but when I go and dig it up it says that the cookie doesn't exist.
code for setting the cookie on muggy8.x10.mx/mmc/user/spicific-user.html
$.cookie('JSONdata', "muggy8#gmail.com.json", { expires: 7 });
the code for getting the cookie on my.matrixcomposer.tk (which provides a frame which contains muggy8.x10.mx/mmc in it)
var json = $.cookie('JSONdata');
when I go and upll up the cookie called JSONdata, it returns undefined.
thanks for helping.
Try setting cookie using path:
$.cookie('JSONdata', "muggy8#gmail.com.json", { expires: 7, path: '/' });
You're trying to access cookies from another domain. The Javascript on my.matrixcomposer.tk can only see cookies set on that domain (or parent matrixcomposer.tk domain). Even if you have the iframe in there for another site, that doesn't override the security of the cookie's domain. Javascript running on one domain cannot directly access the cookies for another domain, even if there is content in the page from that other domain.

Cannot delete cookies that were set in JavaScript on the server

I am trying to write PHP code to delete all of the user cookies on my domain.
Here is what I got:
<?php
$domain = 'www.example.com';
$deleteExpiration = time() - 60*60*24*365*10; // 10 years ago
foreach (array_keys($_COOKIE) as $cookie) {
setcookie($cookie, 0, $deleteExpiration, '/', $domain);
}
Running this code on http://www.example.com/delete_cookies.php deletes all cookies that were set on the server, but not cookies that were set in JavaScript.
I verified using the Firefox Cookies dialog that the problematic cookies are indeed from (path=/; domain=www.example.com). Using Live HTTP headers, I can see that the following header is sent:
Set-Cookie: CookieName=0; expires=Fri, 12-Mar-1999 19:36:15 GMT; path=/; domain=www.example.com
So I believe the setcookie command is working as expected. Firefox is just not honoring the request.
One additional thing that I noticed is that if I set a cookie with domain=www.example.com on the server, then it is listed in the Firefox cookie dialog with domain=".www.example.com", but if I set the following cookie using JavaScript code then the leading dot is not added.
What am I doing wrong? How can I delete these cookies?
I've had a similar issue and it was solved by just not passing the domain.
setcookie($cookie, '', 1, '/');
On a side note from cookie_spec "Setting the path to a higher-level value does not override other more specific path mappings. If there are multiple matches for a given cookie name, but with separate paths, all the matching cookies will be sent." So if you have same name cookies at different path locations you will have to delete each one.

Categories

Resources