Retrieving cookies - javascript

I was wondering how I could retrieve a cookie that has a path specified - something like path=/foo/bar... If I use document.cookie that only retrieves me JSessionId cookie.. which I guess is the only one with path=/.

Are you trying to retrieve the cookie based on the path and not the name? It's possible to have many cookies that match a specified path. Also have a look at jQuery and the Cookie plugin. Setting and retrieving cookies is as easy as:
// get cookie
$.cookie(COOKIE_NAME)
// set cookie
$.cookie(COOKIE_NAME, 'test', { path: '/your/path', expires: 7});
http://plugins.jquery.com/project/cookie

I have figured out how to solve the problem... Just to let anyone reading this, the idea was to test one of the applications for cross site scripting attack (xss), and the cookie contained valuable information that i wanted to retrieve. The problem was that the cookie was on the other path than the web app itself. I had to access the app using /somedomain/project and the cookie had the /somedomain/project/project path set. SO I somehow had to open /somedomain/project/project url to be able to retrieve the cookie I needed. To get to that cookie I have injected an iframe element. inside that iframe element i made an ajax call. it was a dummy call to /somedomain/project/project/ just to get some information in the iframe ant to make sure iframe's document objects get created. that iframe's document object contained the cookie that i needed. After that I have made an XmlHTTPRequest call to a remote service and sent the cookie as a parameter to the remote server.

Related

How I get JavaScript localStorage value after redirect to another page in vue js [duplicate]

I am storing a value in local storage in one domain. Can I retrieve that value from another domain if I am accessing both domain from same browser?
No, you can't use the local storage of one domain to other domain.
Local Storage is domain based. You can’t read or write from localstorage that’s on different domain even on it's subdomain.
you can use it via Iframe on your subdomain.
Please go through this article Cross-Domain LocalStorage for detailed explanation.
Hope it'll help. :)
Yes, you can use this javascript library.
Bifrost-cors size: <2KB
It's very simple to use, you just need to invoke method.
// In www.exampleA.com site:
var bifrostCors = new bifrostCors("http://exampleB.com/", false)
// In www.exampleB.com site
var bifrostCors = new bifrostCors("http://exampleA.com/", false)
bifrostCors.getLocalStorage("local-storage-key-of-what-you-want")
Actually this lib render the iframe (hidden) and uses window.postMessage to communicate with two different contexts (domain).
You can also implement by yourself but this lib is very very light < 2Kb.
Also not only you can access localStorage you have feature also like.
Get/Set Cookie
Bi-directional message thread
Run JS expression from one domain to other
DOM Manipulation from one domain to other domain ( Iframe )
You may want to take a look at this blog post. It seem to suggest that you can attempt to use an iframe as a workaround to access local storage from another domain.
Disclaimer: I haven't tried it before but it seems interesting. Let me know if it works!

Trying to Build a iframe that takes Gradio Link as Source as displays the resulting model output

I am trying to build a SPA which would input box that would take a Gradio Link, (Gradio is simple tool to build Interface for ML Models). Now, I am using an Iframe that takes the user input URL and displays the result. Something like:
Problem is Gradio Link should not be kept open and some authorizations need to be kept.
Approach 1: Tried using Axios get request to make request to URL and display the content in iframe as srcDoc, but while trying to run the model in iframe it fails as returned HTML file as relative paths, example /run/predict.
Approach 2: Tried directly using <iframe src={url}/>, assuming origin Cookie (SPA authentication tokens) would be transferred to destination where I can verify User and send the response, but the cookies in the origin domain are not being transferred to source URL.
Now, for method 1 I need to intercept all the request going out from nextjs with user input URL, example /run/predict to url/run/predict. Nextjs Allows to proxy but when request is of type api/run/predict.
For method 2: I need to send the origin cookie to destination (Source URL). Tried, setting cookie sameSite: None, and secure to true, but still not receiving cookies on destination URL.
Can anyone help me with what could be a possible solution for method 1 or 2 or I am approaching wrong way then please suggest me with right one.

How to remove localStorage key of different domain? [duplicate]

I am storing a value in local storage in one domain. Can I retrieve that value from another domain if I am accessing both domain from same browser?
No, you can't use the local storage of one domain to other domain.
Local Storage is domain based. You can’t read or write from localstorage that’s on different domain even on it's subdomain.
you can use it via Iframe on your subdomain.
Please go through this article Cross-Domain LocalStorage for detailed explanation.
Hope it'll help. :)
Yes, you can use this javascript library.
Bifrost-cors size: <2KB
It's very simple to use, you just need to invoke method.
// In www.exampleA.com site:
var bifrostCors = new bifrostCors("http://exampleB.com/", false)
// In www.exampleB.com site
var bifrostCors = new bifrostCors("http://exampleA.com/", false)
bifrostCors.getLocalStorage("local-storage-key-of-what-you-want")
Actually this lib render the iframe (hidden) and uses window.postMessage to communicate with two different contexts (domain).
You can also implement by yourself but this lib is very very light < 2Kb.
Also not only you can access localStorage you have feature also like.
Get/Set Cookie
Bi-directional message thread
Run JS expression from one domain to other
DOM Manipulation from one domain to other domain ( Iframe )
You may want to take a look at this blog post. It seem to suggest that you can attempt to use an iframe as a workaround to access local storage from another domain.
Disclaimer: I haven't tried it before but it seems interesting. Let me know if it works!

How to migrate cookie domain and retain the value

Is it somehow possible to migrate domains from a cookie?
I have a trackingscript witch sets a cookie on the domain of the tracking script(server side, RoR backend) lets say mytracking.com.
The tracking script itself is integrated as javascript on the domain mycustomer.com.
Status quo is, every guest on the website mycustomer.com has now a cookie for the domain mytracking.com.
Can I somehow migrate the cookie domain from mytracking.com to mycustomer.com?
In your client side JavaScript, generate a unique ID. Then create an iframe with a source pointing to a script on mytracking.com and the unique ID as a parameter.
var ifrm = document.createElement('iframe');
ifrm.setAttribute('src', 'mytracking.com/storecookie.rb?uuid=<UUID>');
document.body.appendChild(ifrm);
Now the storecookie.rb script can access the cookie value on the mytracking.com domain and writes it to a database along with the UUID that you generated.
Now, in your client side JavaScript, you fetch() another script, for example mytracking.com/readcookie.rb?uuid=<UUID> that retrieves the matching cookie value from the database. With the value in your client side JS, you can simply create a new cookie with the correct domain.
Unfortunately that process is a bit convoluted, but cross-domain security prevents setting a cookie for another domain.

How to prevent direct access to my JSON service?

I have a JSON web service to return home markers to be displayed on my Google Map.
Essentially, http://example.com calls the web service to find out the location of all map markers to display like so:
http://example.com/json/?zipcode=12345
And it returns a JSON string such as:
{"address": "321 Main St, Mountain View, CA, USA", ...}
So on my index.html page, I take that JSON string and place the map markers.
However, what I don't want to have happen is people calling out to my JSON web service directly.
I only want http://example.com/index.html to be able to call my http://example.com/json/ web service ... and not some random dude calling the /json/ directly.
Quesiton: how do I prevent direct calling/access to my http://example.com/json/ web service?
UPDATE:
To give more clarity, http://example.com/index.html call http://example.com/json/?zipcode=12345 ... and the JSON service
- returns semi-sensitive data,
- returns a JSON array,
- responds to GET requests,
- the browser making the request has JavaScript enabled
Again, what I don't want to have happen is people simply look at my index.html source code and then call the JSON service directly.
There are a few good ways to authenticate clients.
By IP address. In Apache, use the Allow / Deny directives.
By HTTP auth: basic or digest. This is nice and standardized, and uses usernames/passwords to authenticate.
By cookie. You'll have to come up with the cookie.
By a custom HTTP header that you invent.
Edit:
I didn't catch at first that your web service is being called by client-side code. It is literally NOT POSSIBLE to prevent people from calling your web service directly, if you let client-side Javascript do it. Someone could just read the source code.
Some more specific answers here, but I'd like to make the following general point:
Anything done over AJAX is being loaded by the user's browser. You could make a hacker's life hard if you wanted to, but, ultimately, there is no way of stopping me from getting data that you already freely make available to me. Any service that is publicly available is publicly available, plain and simple.
If you are using Apache you can set allow/deny on locations.
http://www.apachesecurity.net/
or here is a link to the apache docs on the Deny directive
http://httpd.apache.org/docs/2.0/mod/mod_access.html#deny
EDITS (responding to the new info).
The Deny directive also works with environment variables. You can restrict access based on browser string (not really secure, but discourages casual browsing) which would still allow XHR calls.
I would suggest the best way to accomplish this is to have a token of some kind that validates the request is a 'good' request. You can do that with a cookie, a session store of some kind, or a parameter (or some combination).
What I would suggest for something like this is to generate a unique url for the service that expires after a short period of time. You could do something like this pretty easily with Memcache. This strategy could also be used to obfuscate the service url (which would not provide any actual security, but would raise the bar for someone wanting to make direct calls).
Lastly, you could also use public key crypto to do this, but that would be very heavy. You would need to generate a new pub/priv key pair for each request and return the pubkey to the js client (here is a link to an implementation in javascript) http://www.cs.pitt.edu/~kirk/cs1501/notes/rsademo/
You can add a random number as a flag to determine whether the request are coming from the page just sent:
1) When generates index.html, add a random number to the JSON request URL:
Old: http://example.com/json/?zipcode=12345
New: http://example.com/json/?zipcode=12345&f=234234234234234234
Add this number to the Session Context as well.
2) The client browser renders the index.html and request JSON data by the new URL.
3) Your server gets the json request and checks the flag number with Session Context. If matched, response data. Otherwise, return an error message.
4) Clear Session Context by the end of response, or timeout triggered.
Accept only POST requests to the JSON-yielding URL. That won't prevent determined people from getting to it, but it will prevent casual browsing.
I know this is old but for anyone getting here later this is the easiest way to do this. You need to protect the AJAX subpage with a password that you can set on the container page before calling the include.
The easiest way to do this is to require HTTPS on the AJAX call and pass a POST variable. HTTPS + POST ensures the password is always encrypted.
So on the AJAX/sub-page do something like
if ($_POST["access"] == "makeupapassword")
{
...
}
else
{
echo "You can't access this directly";
}
When you call the AJAX make sure to include the POST variable and password in your payload. Since it is in POST it will be encrypted, and since it is random (hopefully) nobody will be able to guess it.
If you want to include or require the PHP directly on another page, just set the POST variable to the password before including it.
$_POST["access"] = "makeupapassword";
require("path/to/the/ajax/file.php");
This is a lot better than maintaining a global variable, session variable, or cookie because some of those are persistent across page loads so you have to make sure to reset the state after checking so users can't get accidental access.
Also I think it is better than page headers because it can't be sniffed since it is secured by HHTPS.
You'll probably have to have some kind of cookie-based authentication. In addition, Ignacio has a good point about using POST. This can help prevent JSON hijacking if you have untrusted scripts running on your domain. However, I don't think using POST is strictly necessary unless the outermost JSON type is an array. In your example it is an object.

Categories

Resources