Warm tip: This article is reproduced from stackoverflow.com, please click
azure-active-directory javascript oauth-2.0 powerbi

Access Token using JavaScript (CORS Policy) error

发布于 2020-05-26 18:37:29

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!

Questioner
Mittal Patel
Viewed
132
Tony Ju 2020-03-11 09:38

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.