I want to authenticate against the oath2/token url using code:
I have managed to do this using c# and httpClient object but when I want to do it using javascript I get the following error:
Access to XMLHttpRequest at 'login.microsoftonline.com/.../token' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
I don't get why this error occurs. Both the c#-code and javascript code are running from my local dev-machine at this moment.
The javascript code is as follows:
(I tried using the "insert code" function for the code below but it just froze the window)
var clientId = "76549cbb-xxxx-xxxx-xxxx-5437229398b9";
var clientSecret = "-ZO8Q~r23Yr4N2e1TOUVvxxxxxxxxxxxxxxxx";
var tenantId = "b2a45cb3-xxxx-xxxx-xxxx-f125697c41e2";
var resource = "">xxxxxxxtest.api.crm4.dynamics.com";
var version = "9.2";
var webapiurl = `${resource}/api/data/${version}`;
var authurl = `login.microsoftonline.com/.../authorize`;
var microsoftTokenUrl = `login.microsoftonline.com/.../token`;
var grantType = "client_credentials";
$.support.cors = true;
function GetAuthroisationToken() {
var token = null;
$.ajax({
url: microsoftTokenUrl,
type: "POST",
contentType: "application/x-www-form-urlencoded",
crossDomain: true,
dataType: "json",
async: false,
data: {
resource: resource,
client_id: clientId,
client_secret: clientSecret,
grant_type: grantType,
},
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, xhr) {
token = data.access_token;
},
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
},
});
return token;
}