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

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.

Related

Restrict PHP API for specific domains which are saved in my database

I have created an API which takes the hostkey or API_KEY and then it validates and gives back JWT token. Everything is working fine, I can't access the restricted routes without Hostkey.
ISSUE
The major issue is that what will happen if someone gives this hostkey to others as it will no longer be protected or it will be misused. So what I want to do is not only validate the hostkey but also validate the domain from which request came from. It is kind of paid service and I really want to restrict is to specific domains. Just like google does with MAP Api as if we add that map key to other domain it throws an error.
The only way to do this is to check the origin and referrer headers.
Unfortunately, server to server this can't be done reliably as the referrer and origin headers would be set by the coder and so can be spoofed easily. For server to server calls you would be better off whitelisting IP addresses that are allowed to make calls to your APIS. In this case use something like How to get Real IP from Visitor? to get the real IP of the server and verify it against whitelisted IPs.
Assuming this is a JS call in browser and not server to server, and that you trust the browser, the only way this can really be done is by verifying the referrer and origin headers. This can still be spoofed with a browser plugin or even with a tool like Postman so I don't recommend it for high security. Here is a PHP example for verifying the origin or referrer.
$origin_url = $_SERVER['HTTP_ORIGIN'] ?? $_SERVER['HTTP_REFERER'];
$allowed_origins = ['example.com', 'gagh.biz']; // replace with query for domains.
$request_host = parse_url($origin_url, PHP_URL_HOST);
$host_domain = implode('.', array_slice(explode('.', $request_host), -2));
if (! in_array($host_domain, $allowed_origins, false)) {
header('HTTP/1.0 403 Forbidden');
die('You are not allowed to access this.');
}
Optionally also CORS headers are good as commented by #ADyson Cross-Origin Request Headers(CORS) with PHP headers
I would like to suggest making a quote or limit for the number of request, so when the paid API reach for 100 request the key will stop working, then the person who paid will not give the key for others. This is not perfect solution, but I would suggest it cause most API services uses it.

Cookie set by Flask app sent but not stored

I have a backend Flask app running on localhost:3000 and a React front-end app running on localhost:5000. In my backend app I am using Flask's 'Response.set_cookie' to set a cookie:
resp = make_response({}, 200)
resp.set_cookie('my_cookie_name', 'my_val', max_age=604800, domain='127.0.0.1', samesite='Lax', secure=None, httponly=None)
I am also allowing cross-origin for all responses in my flask app as follows:
# Child class of Flask to override some features
class TailoredFlask(Flask):
# Override make_response
def make_response(self, rv):
# Call default version from partent
resp = super().make_response(rv)
# Add CORS header to every response
resp.headers["Access-Control-Allow-Origin"] = "*"
resp.headers["Access-Control-Allow-Methods"] = "GET,POST,OPTIONS,HEAD"
resp.headers["Access-Control-Allow-Headers"] = "Origin, X-Requested-With, Content-Type, Accept, Authorization"
return resp
My client accesses my flask cookie endpoint with a call to fetch.
In the Chrome dev tools I can see that the cookie is sent with the HTTP response from my backend. It is visible when on the Network->Cookies tab when I select the request to my backend. However, if I go to the Application tab in the dev tools, my cookie is not there.
It seems like chrome is silently discarding my cookie. I have seen several simiar issues here on SO but none of them seem to explain what is going on or provide a solution to my issue.
I'm also confused about the cookie options. There is a 'domain' option which I've read is to allow cross domain operation for the cookie. However, everything is running on localhost so I feel that I shouldn't need this unless the port is causing issues. However, I have also read that the port should not be included in the cookie 'domain' field.
If anyone can help to explain this to me I would greatly appreciate it because I'm just going round in circles with this stuff.
One more thing to note: I am pointing the browser at 'localhost', but the API call to my backend and the cookie domain both use '127.0.0.1', since I've read elsewhere that the 'domain' field must have at least two dots in it. (I don't have a choice in the browser URL since I am using AWS cognito login UI to redirect to my app after login. Cognito allows http for 'localhost', but only allows https for '127.0.0.1' so I have to use 'localhost' for development.) Could the missmatch between the browser url and cookie domain be causing this issue? Or is there something else that I'm missing?
Ok, so I think I now understand what's going on here, although I don't think there's a fix for my specific problem. As described in this thread browsers (including Chrome) will not allow a domian of 'localhost' within a cookie (I just wish there was a message in the console or something to indicate why the cookie is not being saved, rather than a silent fail!)
There are various suggestions for workarounds, such as using '.app.localhost' to access the application. Unfortunately this is not an option for me as I am redirecting to my front-end app from AWS Cognito, and the only domain that is supported with HTTP (rather than HTTPS) is 'localhost'. Variants such as '.app.localhost' or '127.0.0.1' are not allowed.

Salesforce Integration INVALID_SESSION_ID using Postman

When hitting https://login.salesforce.com/services/oauth2/token, using Postman.
POST https://login.salesforce.com/services/oauth2/token
Response:
I receive a token, but when I try to do something as simple as GET /limits,
GET https://na73.salesforce.com/services/data/v45.0/limits
the response is:
[
{
"message": "Session expired or invalid",
"errorCode": "INVALID_SESSION_ID"
}
]
The strange thing is that when I change all my credentials to a free "developer account" created with a different email address, everything works fine. All requests and headers are the exact same, with the exception of the values from either account.
After digging through a lot of threads on here I thought that maybe my production account (the one I'm posting from now) was not API ENABLED. It turns out my production account is API ENABLED.
I also tried changing https://login.salesforce.com/services/oauth2/token to https://na73.salesforce.com/services/oauth2/token as some threads have suggested, but that just times out.
When comparing both account permissions, they seem identical and I've confirmed I have no issues with the credentials (client id, client secret, security token, access-token), all of them seem to be copied in correctly.
Any ideas for a salesforce noob?
I actually fixed this after banging my head on it forever. You need to go into the settings tab and turn on the Follow Authorization Header setting.
I'm here in 2021 and for me the solution was not 'Follow Authorization Header', but the access token had a different instance_url than expected. Use this instance_url value in _endpoint and you are fine.
After fighting with this for a few days, I've ruled out this is an issue with Postman. What garbage. Just follow https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/quickstart_code.htm and use curl commands instead. If I copy a raw curl command into postman then run, it continues to fail with INVALID_SESSION_ID, but works fine in ZSH
So much for a useful GUI
In my case, the _endpoint variable was not getting set after successfully authorising via the browser (should that not happen automatically?), so I had to set it manually -- but, I put the wrong URL for it (
https://whatever.lightning.force.com instead of
https://whatever.my.salesforce.com),
so I would get a 302 redirect to the correct URL, but then that one would return this message.
So changing the _endpoint variable to the correct URL fixed it for me.
I had the same issue, even when activating the Follow Authorization Header
Basically, the Authorisation Bearer is not set directly, so I added it in the Pre-request script tab
pm.request.headers.add({key: 'Authorization', value: 'Bearer {{_accessToken}}' });
Works like a charm now.

uploading images - do they have domain name in them - chrome not sending session id

For testing I downloaded images from the net and uploaded using valum file upload in chrome...chrome is not sending session cookie along with these request header( I dont see that in the server side/though I see it on developer tool)...does chrome know that these images are from different domain . what is happening...Is there work around for this to pass the session id (as cookie). It is also happening in IE10 which makes me belive it is some standard. and not just a chrome issue. This problem is not there with firefox/safari/opera
It is fine when uploading to localhost. only when uploading to different server with domain name there is this problem leading to creating a new session for this.
Update:
I have added xhr.withCredentials = true still no use.
Also added on the server side to the upload url...
res.setHeader 'Access-Control-Allow-Origin', '*'
res.setHeader 'Access-Control-Allow-Credentials', true
I dont know how helpful this would be, because I would have already sent the upload file and response header will not of much help.
basically the problem is I don't have access to the session variable at the server side, since the session id/sid cookie is not coming back /I am not able to save some of this upload details into the current session(because this is a new session) .
Update:
I tried creating an image in teh desktop using paint..even then chrome would not sent the cookies. Really drives me crazy...
First of all, to get the basics out of the way, this is unrelated to the origin of the image. Chrome or other browsers don't care where you get your images.
It's rather difficult to guess exactly what's going on, would have helped to see a jsfiddle or some more setup explanation, but based on what I'm guessing, you might be using different domains for the page where the upload button is hosted and the target url where you're sending your files (even using ssl for one and http for the other makes it different). Even different subdomains will not allow cookies to be passed if the cookies were not set with a base domain (yourdomain.com)
So, if sub-domains are the problem, you know what to do - set a base domain so you get your cookies to go on any sub domain.
If it's http vs. https you need to always use https (or http) because you can't switch cookies between those two.
If that's not it, or if you're using completely different domains, you can access your cookies locally via script (if they're not marked as http only) and add them to the upload request. Valum 2.0 (don't know about v1.0) lets you add parameters to the request like so:
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/server-side.upload',
// additional data to send, name-value pairs
params: {
param1: 'value1',
param2: 'value2'
}
});
You can't set cookies on a domain which is not the page's domain via script so for using completely different domains your only choice is using request params.
It is possible that the uploader is using Flash under some circumstances to do the upload. There is a bug in Flash which prevents cookies being sent for these types of requests. This would explain the behaviour you are seeing. The workaround is to pass in the sessionId and transmit it in a different way eg. querystring.

Couchdb cors problems

I'm trying to use jquery.couch.js to do couch operations in my ember.js app, but I'm having cors problems, and I have no clue what a good solution is.
It seems to me that couch running on port 5984 would make it basically unusable? Why do requests to different ports cause cors problems? And how on earth do OTHER people end up getting couch to work? I'm immensely confused, and not sure how to proceed.
My couch instance returns this from curl:
{"couchdb":"Welcome","version":"1.2.0"}
The code I'm unsuccessfully trying to run is this:
$.couch.urlPrefix = "http://127.0.0.1:5984";
$.couch.login({
name: 'name',
password: 'secret'
});
I've modifed the urlPrefix part several times to things like localhost and removing the http:// for both versions.
The error it's throwing:
XMLHttpRequest cannot load http://127.0.0.1:5984/_session. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
Help me! I humbly recognize my noobiness for saying this, but how is couchdb even useful if this is built right into the basic functionality?
Oh and I'm including jquery.couch.js like this:
<script src="http://localhost:5984/_utils/script/jquery.couch.js"></script>
Using this version of jquery:
jQuery JavaScript Library v1.10.2
and using jquery migrate because of previous issues:
<script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script>
Edit
I just now tried to add crossDomain: true, xhrFields: {withCredentials: true} to my login call, to no avail. Exact same error message. I'm clearly missing a core concept.
The message you are seeing is referring to the server, not the client. Changes made to the client's call will not, as you reported, change the result.
In CouchDB 1.4 specifically, CORS support must be explicitly enabled and an origins declaration must be made. That said, depending on how you are using your CouchDB instance there are two ways to enable it:
Change the setting in your local.ini directly and restart your instance, see here for more info: http://wiki.apache.org/couchdb/CORS
In the case you have futon available, go to Settings and find the setting there and enable it, in this case no restart is needed.
Update
It seems that the CORS section is not always existent by default, in this case just add it yourself.
Hope it helps.
For those who are using Cookie authentication (not password authentication) and are reusing the cookie in the Ajax request returned by the CouchDB server, you still need to do this in your $.ajax() requests to CouchDB:
xhrFields: {withCredentials: true},
Which, means you have to open the jquery.couch.js file that you sourced from the couch server and manually insert that option into the javascript.
CORS didn't work for me without both doing this on the client side and setting "credentials=true" on the server side.
The original jquery.couch.js as it is written right now doesn't support the client side sending Cookies with CORS, so you have to do it yourself until someone opens a ticket to get this fixed.

Categories

Resources