Can I use localhost as the domain when setting an HTTP cookie? - javascript

I am using a jQuery plugin to set cookies and when I use localhost for the domain it will not store the cookie.
Here is the plugin I am using with jQuery 1.2.6.
http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/
Below is the code that I am using. You can see it does not like localhost, and I am running it from a development web server on localhost. One detail is that I am running off port 4005 but that should not affect the domain, AFAIK.
$(function() {
console.log('Testing');
var one = $.cookie('Test.One');
var two = $.cookie('Test.Two');
var three = $.cookie('Test.Three');
console.log(['one', one]);
console.log(['two', two]);
console.log(['three', three]);
$('#div1').text(one);
$('#div2').text(two);
$('#div3').text(three);
$.cookie('Test.One', 'Test 1');
$.cookie('Test.Two', 'Test 2', { path: '/' });
$.cookie('Test.Three', 'Test 3', { path: '/', domain: 'localhost' });
});

I had similar problem with setting cookies. Make up a domain name and add it to your hosts file as 127.0.0.1. Then run web application on that domain.

I think the domain name of a cookie must have exactly two dots (not counting the final dot after the TLD). So .something.localhost is okay, .google.com is okay, but .localhost or google.com is not. But a glance at RFC 2965 suggests that it's more complicated than that... you might want to read that document, especially section 3.3 (and/or its precursor, RFC 2109).

I updated the jQuery plugin to not add the domain to the cookie when it is localhost. That solves my problem without touching the hosts file.
var domain = (options.domain && options.domain !== 'localhost') ? '; domain=' + (options.domain) : '';

I'm using Code Ignitor, and setting the domain to an empty string fixed my problem while working on the application on localhost. I believe this is the better solution as everyone in the development team then doesn't need to mess with their hosts files on Windows.
Production domain values can be put in the config.php of Code Ignitor when deployed on a live site.

I tried setting the host file to use an alternate name (local.acme.com) and I can now set cookies on that domain. It seems I cannot set cookies on localhost, at least not with Firefox. I do not recall that being a restriction for cookies. I would like to understand what is going on here.
Also, I did try just making the domain in the hosts file simply "dev" but that did not work. I had to use a name that ended in .com or another tld to make it work.

Simplest solution for me to resolve this was to use 127.0.0.1 instead of localhost ;-)
That works fine in Firefox!

Cookie needs to specify SameSite attribute, None value used to be the default, but recent browser versions made Lax the default value to have reasonably robust defense against some classes of cross-site request forgery (CSRF) attacks.
Along with Domain=localhost your cookie should look something like this
document.cookie = `${name}=${value}${expires}; Path=/; Domain=localhost; SameSite=Lax`;
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite

Related

MVC Cookies not seen by JavaScript

Here's the JavaScript code:
var tmp = escape(document.cookie.match(/TestSession=[^;]+(;|$)/)[0]);`
With MVC, if I have this it works:
var cookie = new HttpCookie("TestSession", "SomeValue") {
Expires = DateTime.Now.AddYears(1)
};
But if I add:
cookie.Domain = "Test.com";
or
{ Expires = DateTime.Now.AddYears(1), Domain = "Test.com" };
The JavaScript has tmp as null or undefined.
Any ideas?
Remember, you cannot access cookies of another domain. So, if you're running the site under a different domain than test.com you won't be able to access the cookie.
Note: this will also be true when working from http://localhost - as localhost and test.com are not of the same origin.
To remedy the issue you could check the current host on the server and set the domain accordingly.
Update (after comment)
As noted by Andrei, you could also add a host entry to your local host file that maps test.com to localhost. Though, you'll need to remember to comment it out when you need to navigate to the production version of the site.

location.host vs location.hostname and cross-browser compatibility?

Which one of these is the most effective vs checking if the user agent is accessing via the correct domain.
We would like to show a small js based 'top bar' style warning if they are accessing the domain using some sort of web proxy (as it tends to break the js).
We were thinking about using the following:
var r = /.*domain\.com$/;
if (r.test(location.hostname)) {
// showMessage ...
}
That would take care of any subdomains we ever use.
Which should we use host or hostname?
In Firefox 5 and Chrome 12:
console.log(location.host);
console.log(location.hostname);
.. shows the same for both.
Is that because the port isn't actually in the address bar?
W3Schools says host contains the port.
Should location.host/hostname be validated or can we be pretty certain in IE6+ and all the others it will exist?
As a little memo: the interactive link anatomy
--
In short (assuming a location of http://example.org:8888/foo/bar#bang):
hostname gives you example.org
host gives you example.org:8888
host just includes the port number if there is one specified. If there is no port number specifically in the URL, then it returns the same as hostname. You pick whether you care to match the port number or not. See https://developer.mozilla.org/en-US/docs/Web/API/Location for more info on the window.location object and the various choices it has for matching (with or without port).
I would assume you want hostname to just get the site name.
If you are insisting to use the window.location.origin
You can put this in top of your code before reading the origin
if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
Solution
PS: For the record, it was actually the original question. It was already edited :)
Your primary question has been answered above. I just wanted to point out that the regex you're using has a bug. It will also succeed on foo-domain.com which is not a subdomain of domain.com
What you really want is this:
/(^|\.)domain\.com$/
MDN: https://developer.mozilla.org/en/DOM/window.location
It seems that you will get the same result for both, but hostname contains clear host name without brackets or port number.
Just to add a note that Google Chrome browser has origin attribute for the location. which gives you the entire domain from protocol to the port number as shown in the below screenshot.

Crossdomain TinyMCE

folling this discussion and this link, I learnt that by adding document.domain = 'mydomain.com'; to the tinyMCE initializer file and tiny_mce_popup.js i can overcome the cross domain problem.
I haven't tested it on a proper production server, but in my dev environment the base domain is localhost:8000 and my static files (also tinyMCE ones) are on localhost:88.
Adding document.domain = 'localhost:8000'; or document.domain = 'localhost:88'; doesn't solve the problem as I get the following error:
Uncaught Error: SECURITY_ERR: DOM Exception 18
Any help?
Thanks
The document.domain setting only works if your using subdomains, not completely different domains (different ports count as different domains). So you can have server1.mydomain.com and server2.mydomain.com, in which case you set domain to mydomain.com in both the main page and tiny_mce_popup.js. You can't however use mydomain.com and otherdomain.com. For more information on these restrictions see https://developer.mozilla.org/en/DOM/document.domain or http://msdn.microsoft.com/en-us/library/cc196989(VS.85).aspx
I believe there are plans to adjust the way TinyMCE works so that it can have a CDN version which is usable from any domain, but that doesn't currently exist.
Regards,
Adrian Sutton
http://tinymce.ephox.com
Are you using Django ? I've answered this question below pertaining specifically to tinymce in django.
Tiny MCE popups blank in Django admin

Check in JavaScript if an SSL Certificate is valid

Is there a way to check in JavaScript if given a host its SSL certificate is valid? (non blocking)
In my case, I want to display: "you can also use https://.." if via JavaScript I can make a request to https://my_url without being asked to accept an untrusted certificate.
Can this be done asynchronously?
Take a look here: https://support.mozilla.org/pl/questions/923494
<img src="https://the_site/the_image" onerror="redirectToCertPage()">
This solution is tested and working in current versions of FF and Chrome (as of 2022):
<script> var sslCertTrusted = false; </script>
<script src="https://example.com/ssltest.js"></script>
<script>
if (!sslCertTrusted)
{
alert('Sorry, you need to install the certificate first.');
window.location.replace('http://example.com/cert_install_instructions/');
}
else
{
// alert('Redirecting to secure connection')
window.location.replace('https://example.com/');
}
<script>
You of course need to make your web server return this code under the URL https://example.com/ssltest.js:
sslCertTrusted = true;
I'm not exactly sure about the details. But I've seen similar technology used to detect adblocking etc. You may need to piggyback on the window object maybe, if the variable can't be modified by another script, but generally making the above proof of concept work is left as an exercise to the reader.
What I've found up to now - it is possible with Firefox, don't know yet about other browsers:
https://developer.mozilla.org/En/How_to_check_the_security_state_of_an_XMLHTTPRequest_over_SSL
The straight answer is no. Javascript does not provide any means of validating certificates. This is a job left to the browser.
A better approach to this problem is from the server side. If you are controlling the site, than you can render down a variable on the page with information gleaned on the server side.
In .Net something like
var canSecure = <%= MySiteHasSsl ? "true" : "false" %>;
if (canSecure) {
if (confirm("This site supports SSL encryption. Would you like to switch to a secure connection?")) {
location.href = "https://mysite.com";
}
}
I'm not quite sure what your use case is. If you are just trying to "check ahead of time" before you provide a link to someone for another website then the other answers here will be more relevant than mine.
If you are expecting mysite.com to use an SSL certificate that isn't trusted by default in the browser but you have another way of knowing it should be trusted, then you could use a JavaScript TLS implementation to make cross-domain requests to that other site. However, this requires that your website be served on https and trusted in the browser to begin with and the other site to provide a Flash cross-domain policy file.
If this sounds anything like what you want to do, check out the open source Forge project at github:
http://github.com/digitalbazaar/forge/blob/master/README.md
Useful notice: navigator.clipboard will be undefined on Chrome browsers if there's no valid SSL certificate.
The question doesn't make sense. You can't get the server's SSL certificate without opening an SSL connection to it, and once you've done that, telling the user they can do that too is a bit pointless.
You could run a server elsewhere that handles certificate checks based on whatever you want, then your javascript application sends a request to that server asking for a checkup. This does require that you have at least one server somewhere in the world that you can trust.
A query of this nature can be done in the background quite easily.

Javascript security / cross scripting on same server

Have some Javascript that I need to work via the following:
://localhost
://servername
:/www.domainnamefortheserver.com
When I run the script from http://servername with an IFRAME referencing the domain - it does not load.
Is there a way to get the Javascript security model to recognize the server name, localhost and the domain as the same "domain"?
Thanks
If you are running on UNIX you can edit /etc/hosts to give a fake DNS entry for your server.
eg.
127.0.0.1 localhost www.domainnamefortheserver.com
Then you can always connect to it as the correct name even when it's not on the live site yet. Don't try and break the javascript security directly.
This will also work on OSX. Windows works differently, I expect.
If you are using a server-side language to generate the page, you may be able to set the security domain like so:
document.domain = $CURRENT_HOSTNAME;
So the security domain will be the domain the user requested. This is a shot in the dark, but I hope it helps nonetheless.
Use root relative URIs:
href="/foo/bar"
rather than absolute URIs:
href="http://example.com/foo/bar"
That way the document will be loaded from the same hostname.
What do you mean by
my references are to the domain name
?
If you load scripts in your page on http://servername (using <script src=''>), they will have access to everything on http://servername, even if they come from another domain.
However, if you try to make AJAX calls to the other domain, then you have a problem. You can use the trick explained by Christopher, ie making aliases to the domain.

Categories