OAuth Authentication (with out using ADAL) to Dynamics 365 using Azure Apps


Here I am going to show with out using ADAL(active directory authentication library) how to get the authentication token and how to connect to CRM from a standalone HTML Page using the web-api.

I am not going into detail on how to register an APP in azure and give it access to Dynamics CRM. There are so many wonderful blogs which explains in detail. For App registration follow this blog  powerobjects.com

Change “oauth2AllowImplicitFlow” property value from “false” to “True”  and save it, in Azure app Manifest

Once you’re done with Azure app registration use below code to get the OAuth token.
$.support.cors = true;
var microsoftTokenUrl = "https://login.microsoftonline.com/4060bfe9-7199-xxxxxxx-xxxxxxx/oauth2/token"; //Add your endpoint URL
var clientId = "xxxxxxxx-9715-xxxx-xxxx-3a1fac0cc5fe"; // Add your app ID
var clientSecret = "xxxxxxMJTQmtu4V73cRyduZ6vS40AlkAtSxxxxxxx";//Add your Secret Key
var resource = "https://xxxxxxx.crm5.dynamics.com";//Add your CRM Url
var grantType = "client_credentials";
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(textStatus);
}});
return token;
}

Here is the sample code to create lead in CRM (Design your HTML as your wish)

var entity = {};
entity.subject = $("#subject").val();
entity.firstname = $("#fname").val();
entity.lastname = $("#lname").val();
var salutation = $("#title option:selected").val();
entity.address1_postalcode = $("#postalcode").val();
entity.address1_city = $("#city").val();
entity.address1_stateorprovince = $("#state").val();
entity.address1_country = $("#country").val();
entity.address1_line1 = $("#address").val();
entity.emailaddress1 = $("#email").val();
entity.telephone1 = $("#phone").val();
entity.companyname = $("#company").val();
entity.jobtitle = $("#function").val();
entity.leadsourcecode = 8;
var token = GetAuthroisationToken();
if(token!=null)
webApi_Create("leads", entity, false,token);
function webApi_Create(entityName,entityObject,isAsync,token)
{
var newEntityId = null;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: resource + "/api/data/v8.2/" + entityName,
data: JSON.stringify(entityObject),
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("OData-MaxVersion", "4.0");
XMLHttpRequest.setRequestHeader("OData-Version", "4.0");
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("Authorization", "Bearer " + token);
},
async: isAsync,
success: function (data, textStatus, xhr) {
var uri = xhr.getResponseHeader("OData-EntityId");
var regExp = /\(([^)]+)\)/;
var matches = regExp.exec(uri);
newEntityId = matches[1];
if (newEntityId !== null)
alert("Record Created!");
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
});
return newEntityId;
}