What I'm trying to accomplish:
Create a custom, single-page web application that authenticates with Azure AD, gets a token, and then makes calls (javascript) to the OData endpoint in Dynamics 365 for Operations. Can this be done?
What I have tried:
- Registered custom application in Azure AD and received client ID and set a reply URL
- Created custom ASP .NET web application and added HTML and Script files.
- Added reference to adal.js in my HTML page
- Followed steps on how to authenticate with Azure AD and am successfully getting a valid token
- Sent "GET" request to Dynamics 365 for Operations OData endpoint including the bearer token in the xmlhttprequest header (code below)
What works:
- When I run my application, I have a login button that redirects to the appropriate Azure AD login page
- I am getting a valid token returned to my application page (I have deserialized the token and checked all of the values and they are all good)
What isn't working:
- When I make a simple call to the Odata endpoint including a auth header with the bearer token, I am getting a 401, resource requires user authentication error.
What might be the issue here?
code for the call here:
function retrieveProjects(error, token) { // Handle ADAL Errors. if (error || !token) { errorMessage.textContent = 'ADAL error occurred: ' + error; return; } var req = new XMLHttpRequest() req.open("GET", encodeURI(organizationURI + "/data/Projects"), true); //Set Bearer token req.setRequestHeader("Authorization", "Bearer " + token); req.setRequestHeader("Accept", "application/json"); req.setRequestHeader("Content-Type", "application/json; charset=utf-8"); req.setRequestHeader("DataType", "jsonp"); req.setRequestHeader("OData-MaxVersion", "4.0"); req.setRequestHeader("OData-Version", "4.0"); req.onreadystatechange = function () { if (this.readyState == 4 /* complete */) { req.onreadystatechange = null; if (this.status == 200) { var projects = JSON.parse(this.response).value; renderProjects(projects); } else { var error = JSON.parse(this.response).error; console.log(error.message); errorMessage.textContent = error.message; } console.log(req.responseText); } }; req.send(); }