I am trying to send a cookie from one HTTPS page to another HTTPS page with jQuery cookies.
I set the cookie like so one page 1:
$.cookie('name', variable, { expires: 300 , secure:true});
And then on the next page, I try to get it like so:
console.log( $.cookie('name') );
No dice... is what I am trying to do illegal or immoral in some way?
If it helps, the pages are:
Page 1
Page 2 can be reached by clicking on any of the "Try it Free" buttons.
You can set cookie with domain path:
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
You can read that here:
JQuery Cookie values not maintained while moving from http to https
you can set and get cookie by javascript as well that works fine on https server
set cookie:
document.cookie="username=John Doe";
get cookie:
var x = document.cookie;
delete cookie:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
you can get help from:
http://www.w3schools.com/js/js_cookies.asp
Related
In my node application, I am trying to change my cookie value with the below code. But when I set some cookie values I see it modified in my response header of browser.
Node code :
let nonEncodedString ='s%3A9Q8kumq4BgrHtJPM90ebhhl6OqChsxdp.x0uf93Hk5I03KWeF%2FFT3TM64riv3QAs'
res.cookie('connect.sid', nonEncodedString , { maxAge, httpOnly: true, overwrite: true });
But the header I get is
set-cookie: connect.sid=s%253A9Q8kumq4BgrHtJPM90ebhhl6OqChsxdp.x0uf93Hk5I03KWeF%252FFT3TM64riv3QAs; Max-Age=157680000; Path=/; Expires=Thu, 31 Jul 2025 11:28:35 GMT; HttpOnly
essentially
s%3A9Q8kumq4BgrHtJPM90ebhhl6OqChsxdp.x0uf93Hk5I03KWeF%2FFT3TM64riv3QAs
is changed to
s%253A9Q8kumq4BgrHtJPM90ebhhl6OqChsxdp.x0uf93Hk5I03KWeF%252FFT3TM64riv3QAs. ie. '25' is being added.
I think it's happening because it is getting URL encoded.
I don't want that to happen since its changing the value I am sending and I don't have control to parse it before the browser sets it in the cookie.
you should set an encode function:
res.cookie('connect.sid', nonEncodedString,
{ maxAge,
httpOnly: true,
overwrite: true,
encode: v => v
})
the default encode function is encodeURLComponent.
I have my front end running on one Heroku instance: fe.herokuapp.com
And my back end running on another instance: be.herokuapp.com
I want to set a same domain cookie when a user logs in from the front end.
I am using Koa cookies module to set the cookie like so:
cookies.set("accessToken", token, {
maxAge: 1000 * 60 * 24,
signed: true,
secure: process.env.NODE_ENV === "production",
httpOnly: true,
domain: process.env.ORIGIN_HOSTNAME || "localhost"
})
If it helps, I'm using a React front end and a Node back end (using Koa).
Via Postman, my back end returns the following set-cookie header:
accessToken=<access_token>; path=/; expires=Sun, 01 Sep 2019 16:27:24 GMT; domain=.herokuapp.com; secure; httponly
However, via my React app, I can't see any set-cookie headers.
My front end is using isomorphic-unfetch library with credentials = "include". (perhaps this needs to be same-origin since it's on the same subdomain?)
My two questions are:
Why can't I set the domain value in my cookie from the back end to be fe.herokuapp.com?
Why can I see the set-cookie header via postman but not in my front end React app?
Happy to post more code snippets if need be.
herokuapp.app is listed in Public suffix List which means cookies are blocked from bein set to the domain "herokuapp.com"
you must use custom domain technique
Stuck with this issue for some time. What I figured out:
Need add proxy attribute to app:
const app = new Koa()
app.proxy = true
Extend cookies options with sameSite attribute:
cookies.set("accessToken", token, {
maxAge: 1000 * 60 * 24,
signed: true,
secure: process.env.NODE_ENV === "production",
httpOnly: true,
domain: process.env.ORIGIN_HOSTNAME || "localhost",
sameSite: 'none' // <-- add this
})
Before that I bought a domain for my app. Frontend app point to "domain.com", and Backend app point to "api.domain.com". But now I am not sure if it was necessary.
Chrome and Microsoft IE are aborting a POST response but it's working fine in Firefox. When I run a test through Fiddler I notice the POST headers in Chrome/IE do not contain Cache-Control: max-age=0 and Origin: ... but are otherwise the same.
In Chrome when I press the submit button the POST is sent to the server, processed, and the client aborts the response. After a few reposts, the client finally accepts the response; however the server has already processed the request so it results in duplicate info. This never happens on Firefox, it just always accepts the first response.
It seems to only happen if the request is large (ie: contains a lot more fields for the server to process) leading me to think this has something to do with the time it takes for the server to process the request (in Firefox the request shows as taking about 9 seconds).
Is there something in Firefox that would cause it to wait longer for this response? Or vice-versa, something in IE/Chrome that could be making it end prematurely?
It may not be relevant but this is a Perl Mason site. The response headers in the page which has the form being submitted:
HTTP/1.1 200 OK
Date: Tue, 07 Aug 2018 19:08:57 GMT
Server: Apache
Set-Cookie: ...; path=/
Set-Cookie: TUSKMasonCookie=...; path=/
Expires: Mon, 1 Jan 1990 05:00:00 GMT
Pragma: no-cache
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
It turns out it was Javascript on the page responsible for the reposting. A setTimeout() which recursively called its own function was continuing to be set even after the form data had been posted within the method.
In Chrome/IE/Edge the form submission would be POSTed and the function would continue to set another timeout calling itself. The subsequent call would again POST and abort the connection waiting on the original.
Firefox however would not repost although it too would continue to set and recall the function.
The fix was to add a flag to track when the POST was submitted and when set, to stop the timeout cycle:
function countdown(secs, starttime) {
var d = new Date();
if (!starttime) {
starttime = d.getTime() / 1000;
}
var nowtime = d.getTime() / 1000;
var timeleft = (starttime + secs) - nowtime;
timeleft = Math.max(0, timeleft);
var isposted = false; // <-- Added as fix
if (timeleft == 0) {
isposted = true; // <-- Added as fix
alert("Time is up. Click OK.");
var frm = document.getElementById("frm");
frm.submit();
}
if (!isposted) { // <-- Added as fix
timeout = setTimeout(["countdown(", secs, ", ", starttime, ")"].join(""), 1000);
}
}
i have ajax function like below:
$.ajax({
url:"cookie.php",
type: 'post',
data: {'ok': val},
success:function(data) {
alert(data);
}
});
and my cookie.php for setcookie is:
$name = "mySite";
$value = "stackoverflow.com";
setcookie($name, $value, time() + (86400 * 30), "/");
echo $name."=".$value;
with my ajax function mySite=stackoverflow.com show in my page but cookie not set in browser. why?
Cookies are set using the HTTP Set-Cookie header, sent in the HTTP response when a page first loads.
This header instructs the browser to store the cookie and send it back in future requests to the server.
When you set the cookie with ajax, the browser doesn't reload the current page, and no new headers are sent.
Instead, a new request is sent in the background with XMLHttpRequest, and the cookies are never added to the current page headers, as that page newer reloads and receives the header containing the cookie.
You have to reload the page and get a new set of headers to see the new cookies added in PHP.
There's also the option of setting the cookies in javascript, then they would be visible in the browser right away.
document.cookie="mySite=stackoverflow.com; expires=Thu, 18 Dec 2015 12:00:00 UTC; path=/";
I've read that it could be wise (for caching purposes) to call a file with it's last modified date and let the server resolve it to the original file. In this way you could set caching to for example 10 years and use a static name for a certain version of the file.
However since I also load in javascript asynchronously on my site, I need to be able to do the same in javascript/jQuery.
This is my current code, how would I be able to get the last-modified date of the script in question being loaded?
//load new js
if (typeof loadedScripts[url] === 'undefined') {
$.getScript("javascript/" + url + ".js", function() {
if (typeof window["load_" + url] !== 'undefined') {
promises = promises.concat(window["load_" + url](html));
}
loadedScripts[url] = 1;
});
}
else {
if (typeof window["load_" + url] !== 'undefined') {
promises = promises.concat(window["load_" + url](html));
}
}
(It also executes a function called on load, but that is not interesting for this question)
I know it is possible to get the last modified date of the current document with document.lastModified, but I'm unsure how it would translate into a $.getScript call.
I have also enabled caching:
//set caching to true
$.ajaxSetup({
cache: true
});
For caching purposes, I rather would suggest the ETag.
http://en.wikipedia.org/wiki/HTTP_ETag
We use it for busting the cache if needed and it works great.
However, jQuery's Ajax function provides an ifModified param:
http://api.jquery.com/jquery.ajax/
Here's the explanation:
Allow the request to be successful only if the response has changed
since the last request. This is done by checking the Last-Modified
header. Default value is false, ignoring the header. In jQuery 1.4
this technique also checks the 'etag' specified by the server to catch
unmodified data.
Using this param, the first request to get the Script would look like this:
GET /script.js HTTP/1.1
Host: www.orange-coding.net
HTTP/1.1 200 OK
Last-Modified: Wed, 02 Jan 2013 14:20:58 GMT
Content-Length: 4096
And a second request would look like this:
GET /script.js HTTP/1.1
Host: www.orange-coding.net
If-Modified-Since: Wed, 06 Oct 2010 08:20:58 GMT
HTTP/1.1 304 Not Modified