Hi all,
I am trying to call the CRM 365 web api. After registering the Application on Azure AD I am trying the following code (JS):
//FIRST REQUEST (TOKEN REQUEST)
var req = new XMLHttpRequest();
req.open("POST", "https://login.windows.net/{TENANT}/oauth2/token/", true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200 || this.status === 204) {
if (successCallback) {
if (this.response != null && this.response != "") {
var result = JSON.parse(this.response);
//SECOND REQUEST(401 UNAUTHORIZED)
var req1 = new XMLHttpRequest()
var Id = "73CAC249-4416-E811-A957-00224801AB04";
req1.open("GET", encodeURI("xxxxx.api.crm11.dynamics.com/.../accounts$select=name,address1_city&$top=10"), true);
req1.setRequestHeader("Authorization", "Bearer " + result.access_token);
req1.setRequestHeader("Accept", "application/json");
req1.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req1.setRequestHeader("OData-MaxVersion", "4.0");
req1.setRequestHeader("OData-Version", "4.0");
req1.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
req1.onreadystatechange = null;
if (this.status == 200) {
var accounts = JSON.parse(this.response).value;
}
else {
successCallback(this.response);
}
}
};
req1.send();
}
else
successCallback("OK");
}
} else {
if (errorCallback) {
errorCallback(this.statusText);
}
}
}
};
req.send("client_id=xxxxxx&grant_type=client_credentials&resource=https://xxxx.crm11.dynamics.com&;client_secret=SECRET");
I am able, after the first request to obtain the token, but when I call the second request (passing the token in the header) I receive 401 Unauthorized. Am I missing something?
Thanks in advance.
*This post is locked for comments
I have the same question (0)