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.
Thank you very much for your response, it was helpful. I tried ADAL.js code and I'm successfully getting the id_token in browser URL. I've one follow-up question on RedirectURI. What it should be? I'm embedding Power BI Reports in ServiceNow application. What should be Redirect URI in Azure AD App? Power BI URL or ServiceNow Page URL or something else?