Assistance is required on enabling a cookie to be used cross sub domains. Unable to set the cookie to correct value in javascript. I am not sure if Javascript is failing to set the cookie or MVC.NET is rejecting the request cookie.
Browsers not working
Chrome 43 (Windows)
Firefox 38 (Windows)
iOS 8 Safari
When setting my web.config to use <httpCookies domain=".adomain.com" /> things start to go horribly wrong.
I have some javascript code, in conjuction with pickadate.js datepicker which changes the cookie value to the date selected by a user.
Javascript Function
// Call pickadate API to retrieve selected date
var dateString = this.get('select', 'dd/mm/yyyy');
var cd = new Date();
var exp = cd.setMinutes(cd.getMinutes() + 10)
setCookie("_date", dateString, new Date(exp), "/", ".adomain.com");
window.location.reload();
function setCookie(name, value, expires, path, theDomain, secure) {
value = escape(value);
var theCookie = name + "=" + value +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((theDomain) ? "; domain=" + theDomain : "") +
((secure) ? "; secure" : "");
document.cookie = theCookie;
}
What .NET is doing when it receives the request
Once the datepicker has been changed, it will refresh to page, sending a new request with the date in the cookie. This is picked up a MVC.NET controller. However, the cookie is not changing on the clientside.
if(this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("_date"))
{
cookie.Value = this.ControllerContext.HttpContext.Request.Cookies[sessionDate].Value;
// Do some logic with date to retrieve products
} else {
// Set cookie.value to today's date
}
cookie.HttpOnly = false;
cookie.Path = "/";
cookie.Secure = true;
this.ControllerContext.HttpContext.Response.Cookies.Set(cookie);
The http request contains the following duplicate for _date:
_date=30/07/2015;
_date=31/07/2015;
but the date should equal 31/07/2015, but i have duplicates. The domains are different in the chrome resouce tab.
_date=30/07/2015; domain=.adomain.com << I NEED IT TO BE THIS DOMAIN SETTING
_date=30/07/2015; domain=sub.adomain.com
While I am not a .NET expert, It is possible to explicitly specify the domain for the cookie in the Set-Cookie header. As per RFC 6265, if you specify the domain in the header as example.com then the cookie would be also available to www.example.com and subdomain.example.com. Subdomains are not considered as external domains and hence it is not a security violation.
Probably adding something like this before sending the cookie in your controller should work
cookie.Domain = "adomain.com";
This is not possible because of security reasons. detailed info here
You could try using an iFrame to set the cookie like Facebook does this.
Related
This is how I create my cookie with Javascript and after that redirect to cart page.
var d = new Date();
d.setTime(d.getTime() + (1 * 24 * 60 * 60 * 1000));
var expires = ";expires=" + d.toUTCString();
var product = { productId: btn.value, colorId: productColorId, quantity: 0 };
products.push(product);
document.cookie = "products=" + JSON.stringify(products) + expires + "; path=/; SameSite=strict";
window.location.href = "cart";
and I can find this cookie in my browser in cookie section, but in server side I get nothing.
At first I use this code and I get null.
string products = HttpContext.Request.Cookies["products"];
After that I try this code
if (HttpContext.Request.Cookies.TryGetValue("products", out cookieValue))
{
// TODO: use the cookieValue
}
else
{
// this cookie doesn't exist.
}
and always it runs else, It seems, even don't find cookie.
Is there any suggestion?
According to this documentation,a can optionally be set in double quotes and any US-ASCII characters excluding CTLs, whitespace, double quotes, comma, semicolon, and backslash are allowed.
Try the following changes in your javascript ,use encodeURIComponent() to convert double quotes
document.cookie = "products=" + encodeURIComponent(JSON.stringify(product)) + expires + "; path=/; SameSite=strict";
The screenshot of the cookie value got in the server-side
In response to a comment, Cookie headers in javascript is forbidden, which means it cannot be set programmatically. Only the browser may set it, and it may choose to not send cookie information along with the HTTP request depending on their browser settings. (Typically inside privacy settings)
First I would confirm that the cookie header is indeed being sent. You can usually find this out by using the browser's web inspector and looking at network request. Here is a screenshot in chrome:
If you don't see the cookie header then I would advise double checking browser privacy settings to ensure cookies are enabled and disabling ad/tracking blockers if you have them installed. If this is a case, unfortunately there isn't much you can do other than beg the user to change their settings or disable their ad blockers.
If you DO see the cookie header, then this suggest that it may be a problem in the back-end code, but I'm not familiar with ASP.NET so I can't really comment on that.
Hope this helps
I'm creating cookies which are intended to be shared all across mysite.
This is the code that creates such cookies:
var setCookie = function(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
var path ="path=/;";
document.cookie = cname + "=" + cvalue + ";" + expires + ";" + path;
};
It looks pretty straight forward, and I'm using path=/ to indicate that I want to create or modify always the same cookie all along my site.
The problem is that it is creating one cookie for each URL. With a Mozilla plugin I can see the following:
Cookie Name Value Path
timer_is_enabled true /
timer_is_enabled false /foo
timer_is_enabled true /foo/bar
Which is causing my many bugs because the variables which are being accessed are not one and only, but many independent ones.
Any idea why I'm getting this behavior?
Your code should work as expected, at least regarding the path attribute. Those other cookies may be remnants from earlier tests (sadly, there's normally no way to track the creation date of a given cookie since browsers don't normally keep such information).
I suggest you remove all current cookies from the browser and try again.
That function works ok for me. Ran the following:
setCookie('myCookieKey', 'myCookieValue', 10);
And I got the following:
I'm trying to set my cookies in Javascript the following way
<video id = 'media'></video>
document.addEventListener('DOMContentLoaded', function() {
document.cookie='X-At=$ACCESS_TOKEN$';
document.getElementById('media').src = "$some video link$";
});
However, the cookie just doesn't seem to be added. The file is also hosted on a simpleHttpServer because Chrome seems to ignore pages on local pages. Could someone tell me where the problem is? Note that the cookie gets set when I delete document.getElementById('media').src = "$some video link$";... SoI'm guessing it has to do with setting the source of the element.
Thanks so much.
Found out that cookies are domain specific. So I was unable to set the cookies for the request to a different network, i.e. my file is hosted on a local network 127.0.0.1 and I was trying to send the cookie to a different domain.
The hacky go around for this was to create a proxy server for my request and overwrite the cookie there and redirect the target to my original destination. Couldn't think of a better way to do this.
mate: way of create a cookie like this
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
I created cookie with server side code (c#) and it was shown in chrome developer tools. (Resources->Cookies)
now I created it in js and it is not shown there anymore.
if I write in the console: "document.cookie" - I can see my cookie, but I want to see it in Resources->Cookies so I can easily delete it when I want to.
the code to create the cookie: (from: http://www.w3schools.com/js/js_cookies.asp?output=print)
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
and:
setCookie("myCookie", "true", 365);
Some updates on very similar topic. Secure cookies are not shown on insecure sites.
https://groups.google.com/forum/#!topic/google-chrome-developer-tools/rSbJ1m2F3HY
You need to refresh the resources inspector (small refresh icon in the bottom of the dev tools tray) before it appears.
As from experience, you'll need to refresh the cookies page after you implement the cookie with JS.
Check the cookie settings in your browser and select Allow all cookies option and then refresh the page.
I have found a weird bug in my application and due to my small experience with Javascript I couldn't debug it;
I am trying to set a persistent cookie, which will die after one year from its set (max value in major browsers) but persists and won't be deleted after the browser gets closed. I've been using this code:
// Build the expiration date string:
var expiration_date = new Date();
expiration_date.setYear (expiration_date.getYear () + 1);
expiration_date = expiration_date.toGMTString();
// Build the set-cookie string:
var cookie_string = "test_cookies = true; path=/; expires=" + expiration_date;
// Create/update the cookie:
document.cookie = cookie_string;
I've noticed that the cookie has a session tag when I use cookie manager plugin, and only the ones with this tag get removed when the browser shuts down (others like Wordpress's and such scripts persist).
I changed your syntax over to my style of coding (variables at the top, minimal re-casting, etc.) and the example below works on my localhost quite well.
// Build the expiration date string:
var expiration_date = new Date();
var cookie_string = '';
expiration_date.setFullYear(expiration_date.getFullYear() + 1);
// Build the set-cookie string:
cookie_string = "test_cookies=true; path=/; expires=" + expiration_date.toUTCString();
// Create or update the cookie:
document.cookie = cookie_string;
If you are having problems on a production server, try setting the domain of the cookie as well (www.quirksmode.org/js/cookies.html#link5)
You can also use the max-age attribute.
cookie_string = "test_cookies=true; path=/; max-age=31536000";
One week: max-age=604800
One month: max-age=2628000
One year: max-age=31536000
have you tried using the getFullYear() and setFullYear() methods of the Date instance instead of getYear() and setYear() ? the latter are are deprecated, see here.
hope that helps! cheers.