I'm embedding Power BI Reports into another application using JavaScript and I could generate access token (Barear) using below JavaScript code but it doesn't work in all the browsers. It displays below error message.
Access to XMLHttpRequest at 'https://login.microsoftonline.com/<>/oauth2/token' 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.
I added required request headers but still the same result.
var key;
var request = new XMLHttpRequest();
request.open("POST", "https://login.microsoftonline.com/<<tenant_id>>/oauth2/token", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader('Access-Control-Allow-Headers', 'x-requested-with');
request.setRequestHeader('Access-Control-Allow-Origin', '*');
request.send("grant_type=client_credentials&client_id=<<clientid>>&client_secret=<<clientsecret>>&resource:<<resourceurl>>"); // specify the credentials to receive the token on request
request.onreadystatechange = function () {
if (request.readyState == request.DONE) {
var response = request.responseText;
var obj = JSON.parse(response);
key = obj.access_token;
token_ = key;
}
}
Any ideas?
Thank you!
You should never put the client secret in the front-end.
We suggest you use azure-activedirectory-library-for-js for frontend to integrate AAD with a ease. You can refer to No 'Access-Control-Allow-Origin' header with Microsoft Online Auth for details.
client_credentials grant_type is used in app only scenario. If you must use client credential flow, you need to get the access token in your app's backend and return it to the frontend.
Related
My goal
I am doing .aspx file on Microsoft Visual Studio. What I expect is that the system will scan the QR code and then send the JSON data to the server side.
PS. I am using XMLHttpRequest to send the data.
What I Get
First I tried to pass it directly, it does not work so I check its status and readyStats, what it shows is 1(open) and 0(not initialized) (I am expecting 4(done) and 200(ok)) the responseText is null. I then inspected my browser (Google Chrome), the console shows an error "Access to XMLHttpRequest at 'https://website-A.aspx' from origin 'https://localhost:44371' 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."
What I tried
So I searched for solution on stack overflow, most of them says that I need to put in the header Access-Control-Allow-Origin:* to the server, but the problem is I do not have the control of the server but I do contacted them to change the code to try it out, end up Access-Control-Allow-Origin:* doesn't work so I looked for alternative. I tried to use plugin such as Moesif Origin & CORS Changer but it shows "Access to XMLHttpRequest at 'https://website-A.aspx' from origin 'https://localhost:44371' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.".
Below is my code:
function onScanSuccess(qrCodeMessage) {
...
var url = "https://Website-A.aspx";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}
};
//I hardcoded the data for testing
var data = {
"SOME_ID": "Value",
"SOME_TYPE": "Value",
"SOME_ID": "Value",
"SOME_AMT": "Value",
"SOME_AMT_CURRENCY": "Value",
"SOME_DESC": "Value",
...
};
xhr.send(data);
}
Is there anyway to solve this without changing the server side's code or bypassing the CORS?
I wish to solve this by modify the code in the same .aspx only, is it possible?
If my code ain't going to work, is there any other way to do it?
Any helps will be appreciated.
cors must be allowed on server side. your code looks ok.
sorry, i can't use the comment function yet
I want to made simple post request on Ebay trading api with javascript Ajax. Here is the call format. I got some error on the following request. can anyone tell me the what wrong with the call .
const findbtn = document.querySelector(".find-item-btn");
findbtn.addEventListener("click", getData);
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log(this.responseText);
};
const xml =
'<?xml version="1.0" encoding="utf-8"?>' +
'<GetItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">' +
"<ErrorLanguage>en_US</ErrorLanguage>" +
"<WarningLevel>High</WarningLevel>" +
"<ItemID>232789363104</ItemID>" +
"</GetItemRequest>";
xhttp.open("POST", "https://api.ebay.com/ws/api.dll", true);
xhttp.setRequestHeader("X-EBAY-API-COMPATIBILITY-LEVEL", "967");
xhttp.setRequestHeader("X-EBAY-API-DEV-NAME","6cfe5ebb-73c4-465b-ad24-c4f0aea8de0");
xhttp.setRequestHeader("X-EBAY-API-APP-NAME","RegnantC-SaveWix-PRD-3ef66784f-24730a7");
xhttp.setRequestHeader("X-EBAY-API-CERT-NAME","PRD-ef66784f85c1-6c65-4919-bc83-24c6");
xhttp.setRequestHeader("X-EBAY-API-CALL-NAME", "GetItem");
xhttp.setRequestHeader("X-EBAY-API-SITEID", "0");
xhttp.setRequestHeader("Content-Type", "text/xml");
xhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xhttp.setRequestHeader("Access-Control-Allow-Headers","X-Requested-With, Origin, Content-Type, X-Auth-Token");
xhttp.setRequestHeader("Access-Control-Allow-Methods","GET, PUT, POST, DELETE");
xhttp.setRequestHeader("X-EBAY-API-IAF-TOKEN","v^1.1#i^1#f^0#r^0#p^3#I^3#t^H4sIAAAAAAAAAOVYeWwUVRjv9lJEaIigTUWzTiEeOLtz7e7sh"
);
xhttp.send(xml);
}
and got the following error
1 Access to XMLHttpRequest at 'https://api.ebay.com/ws/api.dll' from origin 'localhost/app' 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.
2 POST https://api.ebay.com/ws/api.dll net::ERR_FAILED
Please help me. is the right format for the ajax request
Actually it's causing the CORS error. You can read about it details from here https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
And if you want to overcome this issue you can enable CORS from server. I mean send the request through your server.
Or you can also use CORS anywhere header.
const corsHeader = "https://cors-anywhere.herokuapp.com/";
then use this corsHeader appending with your url like this,
xhttp.open("POST", corsHeader+"https://api.ebay.com/ws/api.dll", true);
It'll send the request and currently it's showing error: IAF token supplied is invalid. If you provide proper IAF token then it'll provide you the data.
I'm very new to programming in general so this will not be a technical answer in the least, but.... I did get this to eliminate the CORS error.
const corsHeader = "https://cors-anywhere.herokuapp.com/";
xhttp.open("POST", "https://api.ebay.com/identity/v1/oauth2/token", true);
xhttp.open("POST", corsHeader, true);
I had to go here first and enable temporary access though.
https://cors-anywhere.herokuapp.com/corsdemo
Now when I run this the console is saying:
"This API enables cross-origin requests to anywhere."
If I can figure out how to get any farther I will update this thread.
The exact error that I am struggling with is "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.".
I am trying to fetch JSON data using JavaScript from https://api.kraken.com/0/public/OHLC?pair=ETHEUR. I created a XMLHttpRequest object to do this, and specified GET as the type of request. This is supposedly a simple request, however the error says that a preflight request was sent. What is the reason for this behavior? That being said, to fix this error I tried to set a request header in which I specified '*' as the value for the Access-Control-Allow-Origin, yet I still get an error. I have looked through responses to similar questions as mine, but haven't been able to figure out how to solve the problem I am dealing with. This is probably due to still being very new to JavaScript. Either way, below is the code that I have written:
var requestURL = 'https://api.kraken.com/0/public/OHLC?pair=ETHEUR'
var request = new XMLHttpRequest();
request.open('GET',requestURL,true);
request.responseType = 'json';
request.onload = function(){
var data = request.response;
console.log(data);
}
request.setRequestHeader('Access-Control-Allow-Origin','*');
request.send();
In cases like this where the server you’re trying to make a cross-origin request to doesn’t send the Access-Control-Allow-Origin response header, your only option, if you want to make a request to that server from frontend JavaScript code running in a browser, is to use a CORS proxy. Otherwise, your browser won’t allow your frontend JavaScript code to access the response.
So, you can make your request succeed if you change your code to have something like this:
var proxyURL = 'https://cors-anywhere.herokuapp.com';
var requestURL = 'https://api.kraken.com/0/public/OHLC?pair=ETHEUR';
var request = new XMLHttpRequest();
request.open('GET', proxyURL + '/' + requestURL, true);
That sends the request through https://cors-anywhere.herokuapp.com, which forwards the request to https://api.kraken.com/0/public/OHLC?pair=ETHEUR and then receives the response. The https://cors-anywhere.herokuapp.com backend adds the Access-Control-Allow-Origin header to the response and passes that back to your requesting frontend code.
The browser will then allow your frontend code to access the response because that response with the Access-Control-Allow-Origin response header is what the browser sees.
You can also easily set up your own CORS proxy using https://github.com/Rob--W/cors-anywhere/
Note also that request.setRequestHeader('Access-Control-Allow-Origin','*') needs to be removed from the frontend code you are making the request with (as mentioned in comments above).
That’s because Access-Control-Allow-Origin is strictly a response header for servers to send in responses; sending it from the client side in a request will have no effect other than to trigger your browser to do an unnecessary CORS preflight OPTIONS request that will fail.
For details about what browsers do when you send cross-origin requests from frontend JavaScript code using XHR or the Fetch API or AJAX methods from JavaScript libraries—and details about what response headers must be received in order for browsers to allow frontend code to access the responses—see https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.
var proxyURL = 'https://cors-anywhere.herokuapp.com';
var requestURL = 'https://api.kraken.com/0/public/OHLC?pair=ETHEUR';
var request = new XMLHttpRequest();
request.open('GET', proxyURL + '/' + requestURL, true);
request.responseType = 'json';
request.onload = function() {
var data = request.response;
document.querySelector('pre').textContent = JSON.stringify(data, null, 2);
}
request.send();
<pre></pre>
I Request an authorization code from OAuth2 Server.
My purpose is to authorize user with my microsoft App.
Refered Document
My attempt for get Call:
function httpGet(){
var theUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id="client_id"&response_type=code&redirect_uri="redirect_uri"&response_mode=query&resource=https%3A%2F%2Fservice.contoso.com%2F&state=12345";
var req = new XMLHttpRequest();
req.open('GET', theUrl, true);
req.onreadystatechange = function() {
if (req.readyState === 4) {
if (req.status >= 200 && req.status < 400) {
console.log(req.responseText)
} else {
console.log("error")
}
}
};
req.send();
}
but this gives below error:
No 'Access-Control-Allow-Origin' header is present on the requested
resource.
then I add the req.setRequestHeader("Access-Control-Allow-Origin", "*");
but it gives the below error:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
To integrate AAD in javascript, we suggest you to use azure-activedirectory-library-for-js which is a library in javascript for frontend to integrate AAD with a ease.
There are 2 options we need to pay attention on before we use ADAL for JS:
According the node at https://github.com/OfficeDev/O365-jQuery-CORS#step-6--run-the-sample:
Note This sample will not work in Internet Explorer. Please use a different browser, such as Google Chrome. ADAL.js uses an iframe to get CORS API tokens for resources other than the SPA's own backend. These iframe requests require access to the browser's cookies to authenticate with Azure Active Directory. Unfortunately, cookies are not accessible to Internet Explorer when the app is running in localhost.
Enable the oauth2AllowImplicitFlow of your Azure AD application. Refer to https://crmdynamicsblog.wordpress.com/2016/03/17/response-type-token-is-not-enabled-for-the-application-2/ for the detailed steps.
Here is the code sample to acquire access token from Microsoft Graph:
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.10/js/adal.min.js"></script>
<body>
login
access token
</body>
<script type="text/javascript">
var configOptions = {
tenant: "<tenant_id>", // Optional by default, it sends common
clientId: "<client_id>",
postLogoutRedirectUri: window.location.origin,
}
window.authContext = new AuthenticationContext(configOptions);
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
function getToken(){
authContext.acquireToken("https://graph.microsoft.com",function(error, token){
console.log(error);
console.log(token);
})
}
function login(){
authContext.login();
}
</script>
Without using any frontend google libraries I came up with solution.
window.open("url")
After complete the authentication I get the code from url params and send it backend and achieve the access token, refersh token.......etc,
I am trying to subscribe users to my mailchimp list using this snippet:
function subscribeUser(name, email) {
var xhr = new XMLHttpRequest();
var endpoint = 'https://<dc>.api.mailchimp.com/3.0/lists/<list>/members/';
var data = {};
data.email_address = email;
data.status = "subscribed";
data.merge_fields = {};
data.merge_fields.NAME = name;
xhr.open("POST", endpoint, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "apikey <key>");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(data);
}
It generates this error in chrome:
I am unable to write ajax based services to update lists. Because you guys did not add the Access Control header. I cannot send a simple xhr to your endpoint using a modern browser.
XMLHttpRequest cannot load https://<dc>.api.mailchimp.com/3.0/lists/<list>/members/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 501.
Mine is a static website and I would like to keep it that way. No backend is needed, hosted on github. So I need a JS solution to this.
They currently do not allow client-side access to their API. Their response to a similar question in comments:
We do not support accessing the API via client-side Javascript to
avoid the security issue of passing your API Key along to your users.