How can I get data from a server with no 'Access-Control-Allow-Origin' ?
I can get an Opaque answer only.
Problem is that I need to call a public API on a server with no Access-Control-Allow-Origin - I can try to convince site owner to add it, but how do I do it in the meantime ? I am trying to not run a proxy on my own domain. The data is personal data (electric power consumption), which I want the browser to download and process, and I do not want my server to see the users private API key, which is stored in localStorage only. At some point I want to it to become a true web app.
Fetch with no-cors mode gives me Opaque data, and with cors enabled I get:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.eloverblik.dk/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)
Any other way to call an API / Get data from a 3rd party site on the web ?
Here is example code:
fetch( 'https://www.eloverblik.dk', { method: 'GET', redirect: 'follow'})
.then( (response) => { console.log('x'); console.log('Resp: ' + response.type) })
.then((result) => { console.log('Res: ' + result )})
.catch( (error) => { console.error('Error:', error); })
Thanks for the help here.
Basically, the answer is, that it is not possible.
The workaround is to use a reverse proxy like nginx and add the header.
I have contacted the site owner and asked them to add the header. It is a public available API, that requires login with an API key you can generate on a website.
They do run another api server, giving anonymous access to public data. That one is run on cloudapp.net. The one where they "forgot" the header has personal electricity consumption measurements - Down to 15m intervals. It is hosted under t-msedge.net. Hope they will do the change, so I can do away with the proxy.
Related
I'm building a C++ backend with heavy calculations that are meant to work as an JSON API for connecting clients. To accomplish this, I've used HTTPServer in Poco::Net from POCO C++ Libraries.
Unfortunately when building two different clients it turned out that a regular webpage (HTML+JS) can't use Fetch to communicate with the backend due to CORS error. My understanding is that they need to use the same localhost: and that's not the case when manually opening the HTML document on the computer that's also running the backend.
All I can come up with when searching is the generic advice that servers need to enable CORS and whitelist relevant domains. Unfortunately I can't find documentation on how to accomplish this. The only relevant result was an answer on a related question where he recommended the following:
response.set("Access-Control-Allow-Origin", "*");
Naturally whitelisting everything isn't recommended from a security point of view but the main goal here is to just get it running locally to continue the development. Unfortunately it seems to make no difference and the browser console still says:
Access to fetch at 'http://localhost:6363/' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Hovering the error in the Chrome Network tab I get the following:
Cross-Origin Resource Sharing error: PreflightMissingAllowOriginHeader
My current JavaScript call:
const data = { test: 'test' }
fetch('http://localhost:6363', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.text())
.then(message => {
console.log('Data retrieved:', message);
})
.catch((error) => {
console.error('Error:', error);
});
Any suggestions on how to proceed?
Working with Apache Airflow REST API, and having issues with CORS.
When calling the endpoint using the fetch API in JavaScript I get the following error:
Access to fetch at 'my_url/api/v1/dags/example_bash_operator/tasks' from origin 'my_url' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
This is how I am calling it:
let url = "my_url/api/v1/dags/example_bash_operator/tasks";
let username = 'my_username';
let password = 'my_password';
let headers = new Headers();
headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));
fetch(url, {
headers: headers,
method: 'GET',
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
I also tried adding mode: 'no-cors' but just get the "unexpected end of input" error.
For some background, the following works fine:
starting the airflow webserver and scheduler
accessing the airflow UI
accessing the SwaggerUI authenticating Swagger and calling the REST endpoints with this tool
calling my_url in the address bar of a new browser tab (returns the expected JSON)
I have set the auth_backend in airflow.cfg:
auth_backend = airflow.api.auth.backend.default
Although with the latest REST API version I don't think this makes a difference since everything is set to deny.
I have also set the access control headers in airflow.cfg as described in the docs:
access_control_allow_headers = origin, content-type, accept
access_control_allow_methods = POST, GET, OPTIONS, DELETE
access_control_allow_origin = my_url
...and also tried with wildcard for the access_control_allow_origin:
access_control_allow_origin = *
So the REST calls work fine through Swagger and through the browser address bar, but I cannot call it with fetch using JS. Note that the JS is in an index.html file on the same server (and same root directory) as the airflow files.
The described behavior makes sense, since CORS is used by the browser to prevent attacks from scripts of different resources.
You are still able to fetch via Swagger, Postman or other tools, even through the browser via address bar. But if the policy does not allow to fetch from a different origin, then the browser prevents fetching from your script, which is probably served on a different port. Origin contains host and port.
Your main issue, I cannot help with at the moment.
I've faced the issue of not being able to set the origin policy within the Airflow 2.0 server/API through the (docker-compose) environment variable AIRFLOW__API__ACCESS_CONTROL_ALLOW_ORIGIN.
Maybe it's related to your issue, since I can see from the url of your question (containing the v1), that you're are also using Airflow 2.x.
By the way, the message from chrome is CORS error: Preflight Missing Allow Origin Header, referring to the question in the comments of the original question.
I'm trying to get an access token from Azure. I was following this tutorial, but the thing is that the guy's using postman. It works for me in postman as well, but it fails in javascript and I don't understand why.
function getAccessToken() {
fetch(`${loginUrl}${tenantId}/oauth2/token`, {
method: "POST",
body: JSON.stringify({
grant_type: "client_credentials",
client_id: clientId,
client_secret: clientSecret,
resource: resource,
})
})
.then((response) => {
console.log(JSON.stringify(response));
})
.catch((err) => {
console.log(JSON.stringify(err));
});
}
The credentials are good, i.e. the clientId, secret, tenantid etc.
I also tried in PowerShell and it worked:
Invoke-RestMethod `
-Uri "$loginUrl$tenantId/oauth2/token" `
-Method Post `
-Body #{"grant_type"="client_credentials"; "resource" = $resource; "client_id" = $clientId; "client_secret" = $clientSecret }
But on js I get the following error:
Access to fetch at 'https://login.microsoftonline.com/myTenantId/oauth2/token' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I'm running this script in an HTML file for testing purposes at the moment.
If we directly call the rest api from a domain different from your website in the HTML page, we will get CORS issue. This is for safety reasons. For more details, please refer to here.
So if you want to get Azure AD token in HTML page, I suggest you use package msaljs to implement implicit flow to get token. The package has fixed cors issue. Regarding how to do that, please refer to here.
Besides, if you still want to use client credentials flow to get token in your HTML page. You have two choices. One choice is to use proxy server. The proxy acts as an intermediary between a client and server. For future details about it, please refer to the blog.
I'm trying to build a website that requests JIRA data from a company-owned JIRA Board via REST API and displays the requested data in different graphs. While developing with JavaScript I ran into the CORS header 'Access-Control-Allow-Origin' missing error and therefore could not access the data.
Here is some code:
var url = myUrl;
var auth_string = myJira_user + ":" + myJira_password;
var encoded_string = btoa(auth_string);
var http_headers = {
"Content-Type": "application/json",
Authorization: "Basic " + encoded_string
};
var headers = new Headers(http_headers);
fetch(url, headers)
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
})
.catch(err => {});
This JS script throws the above-mentioned error in my browser console, while a simple python script or curl command with the same parameters works and outputs data. How is that possible?
Modern browsers first check CORS policy on the API server via an HTTP OPTIONS call. This is known as "preflighting a request".
CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
HTTP OPTIONS: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS
In effect, the browser first checks with the API server whether it has permission to call and consume APIs from the origin (website where the user is browsing from, identified by domain, protocol, and port). If the API server expects calls to be made from the origin, it returns a success response to the OPTIONS calls and then the browser proceeds to make the GET/POST/etc call. However, if the API server does not recognize the origin from the OPTIONS call, it will return a fail response, and the browser will not proceed with the API call and instead generates the exception you've observerd.
CORS + HTTP OPTIONS is one mechanism in the arsenal of securing API access and mitigating the plethora of security and privacy issues arising from Cross-Site-Scripting.
But to your point, CORS does not impact calls made from non-browser applications. A non-browser application, such as CURL or any code you can write in Python, Node, etc. does not make the OPTIONS calls and therefore, the API server's CORS policies do not apply.
You could setup a middleman/proxy server that receives API requests from your web application, call the target API server, and marshal back the response, therefore circumventing the CORS policy.
I want to make some API requests to the shipping carriers at the BigCommerce product page and I have some credential for that requests which I don't want to show in my JS code. According to the specific environment of BigCommerce I can't make any changes in back end code. I read a lot of similar questions and now have only one question.
Is it only one way to do that using my own API back end web-server which will store credential information and send POST request to the third party API? Then I will receive that information using a POST request via JS to my own API.
I have tried to run Ruby API application on the nginx web-server. However, it was unsuccessful because browser blocked my fetch() request according to the CORS Policy. I tried to add Access-Control-Allow-Origin: * parameter to the server response header writing it in ruby config file but browser didn't recognize it. Also I tried to set up configuration file on the nginx side but that didn't help me with CORS policy response. That's interesting because using Restlet Application I received response from my own API application with correct information and status "ok".
(async function application() {
let dataRuby = {
url: 'http://IP_address/index',
body: {"name": "21312", "year": "2019"}
};
function getApi(data) {
let myInit = {};
myInit.method = "POST";
myInit.body = JSON.stringify(data.body);
myInit.headers = {
'Content-Type': 'application/json'
};
let myRequest = new Request(data.url, myInit);
return fetch(myRequest).then(
res => res.json()
);
}
let response = await getApi(dataRuby);
console.log(response);
})()
Access to fetch at http://IP_address/index from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.