Web API Authentication from JavaScript
Web API, introduced in Dynamics CRM 2016, can be used from within CRM and also Outside CRM. To call Web API from JavaScript outside of CRM we have to implement authentication. In previous versions of Dynamics CRM, CORS was not implemented, so we cannot authenticate or can get Access Token from browsers. We had to use middleware Web Service API or SOAP Authentication to access CRM. CORS, Cross-Origin Resource Sharing, has been implemented in Dynamics CRM 2016 and now we can get access token using Azure Active Directory Authentication Library from JavaScript.
In this tutorial we will learn how to authenticate Dynamics CRM from HTML/JavaScript Web Application using ADAL (Active Directory Authentication Library)
Application
The app takes Dynamics CRM Online URL, username and password and returns the full name of the logged in user. The final application looks like below:
Note: The complete code of the application is hosted on Github
Working
First of all the App must be registered. For Registration Please refer this link : How to Register Dynamics CRM App with Azure Active Directory.
In this App authentication is performed using Azure Active Directory from JavaScript. First of all, Config is created in which details of Tenant, clientId, postLogoutRedirectUri, endpoints and cacheLocation is provided. For Microsoft Dynamics CRM Online, a tenant is the account you create in the Microsoft Online Services environment when you sign up for a CRM Online subscription. Tenant is created as org name preceeded by onmicrosoft.com (<org>.onmicrosoft.com). ClientId and PostLogoutRedirectUri can be found in Azure Active Directory where the App is registered. The config is then passed into AuthenticationContext:
authContext = new AuthenticationContext(config);
Next is to check whether someone is already signed in. If not, then we can Log into the Microsoft online using:
authContext.login();
It will take you to Microsoft Official Login page. Enter the credentials and login. Browser will redirect to the page that is registered in the Azure Active Directory, along with Token which will be used to Acquire Access Token. Access Token can be acquired with the following code:
authContext.acquireToken(resourseURL, callback)
resourseURL is the endpoint from where the data should be accessed. We can also provide callback as when the acquire token is completed that callback is fired with parameters of token and error. We can send the WhoAmI Request to get the get the UserId of the logged in user.
function getUserId(error,token) { var req = new XMLHttpRequest req.open("GET", encodeURI(organizationURI + "/api/data/v8.0/WhoAmI"), true); req.onreadystatechange = function () { if (req.readyState == 4 && req.status == 200) { var whoAmIResponse = JSON.parse(req.responseText); getFullname(whoAmIResponse.UserId) } }; req.setRequestHeader("OData-MaxVersion", "4.0"); req.setRequestHeader("OData-Version", "4.0"); req.setRequestHeader("Accept", "application/json"); req.setRequestHeader("Authorization", "Bearer " + token); req.send(); }
When the WhoAmI Request is finished then using the userId to get the fullname of the logged in user.
function getFullname(Id) { function getUserId(error,token) { var req = new XMLHttpRequest req.open("GET", encodeURI(organizationURI + "/api/data/v8.0/systemusers(" + Id + ")?$select=fullname"), true); req.onreadystatechange = function () { if (req.readyState == 4 && req.status == 200) { var userInfoResponse = JSON.parse(req.responseText); } }; req.setRequestHeader("OData-MaxVersion", "4.0"); req.setRequestHeader("OData-Version", "4.0"); req.setRequestHeader("Accept", "application/json"); req.setRequestHeader("Authorization", "Bearer " + authContext.getCachedToken(organizationURI)); req.send(); }
Conclusion
This simple and pure JavaScript and HTML web site is a great tutorial on how to authenticate JavaScript App with Microsoft Dynamics CRM Web API to access CRM Data.
*This post is locked for comments