MSCRM :: WebApi OAuth Setup

Start from Dynamics CRM 2016, Microsoft introduced new big feature called Web API endpoint. That means we can build our own Web Application, SPA or Mobile Application and play with Dynamics CRM data. In that case we will need a library for Azure AD Authentication to get access token before making requests to CRM Web API and that is Azure AD Authentication Library (ADAL)
In part 1 we will discover how to register our application to Azure AD tenant and use adal.js to authenticate Dynamics CRM online
1. Register application in Azure Active Directory
Access Azure portal(https://portal.azure.com) and go to Azure Active Directory. From App Registrations, add new application.
In this part we will use Active Directory Authentication Library for JavaScript (Adal.js) to handle authentication in our Single Page Application. This library also has another version for AngularJs (Adal-angular.js)
Installation
We can get the library through variety ways:
- Via NPM
npm install adal-angular
- Via CDN
<!-- Latest compiled and minified JavaScript -->
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.13/js/adal.min.js"></script>
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.13/js/adal-angular.min.js"></script>
- Via bower
$ bower install adal-angular
- Or getting source directly Adal.js or Adal-angular.js
In this sample, we will use adal.js for authentication
Configuration:
Base on library from https://github.com/Scaleable-solutions/WebAPIAuthFromJavaScript, I fixed some issued that happened when losing cookie or token expired and updated into util.js (check out my project here)
We need to update information for our application before using Dynamics CRM 365 Web API. So we will updated parameters in util.js like below:
var organizationURI = "https://<ORG_NAME>.api.crm5.dynamics.com"; // TODO: Add your organizationURI
...
var tenant = "b5101e80-6255-4e07-afed-380b2d3bdd51"; // TODO: add your tenant
var clientId = "30156abc-cc53-468f-a1ca-972e1c3b02d6"; // TODO: Add your Client Id
var pageUrl = "http://localhost:61950/Portal/Sample.html";// TODO: Add your Reply URL
ClientId: Your Application ID when you register your app into Azure AD
TenanID: Your Directory ID (in Azure Active Directory) – see image below
Once web page is loaded, authenticate() function will check whether token is available or not
function authenticate() { ... }
If access token is not available, then login button will show up and user can redirect to Azure AD login page
After user is authenticated, user info and access token will be stored in localStorage variable. Then we can use this token to create request to Dynamics CRM Web API from our application
Recent Comments