Archive

Archive for January 1, 2016

CRM 2016 Web API – Impersonate User

January 1, 2016 3 comments

In CRM, Impersonation is possible in Plug-ins (using ‘Run As’ while registering Plug-in step) or using ‘CallerId’ property while instantiating OrganizationServiceProxy.

What if I have to impersonate ‘Retrive’ operation from Jscript? This was not possible.

With advent of CRM Web API with CRM 2016 we can impersonate in Jscript.

What is a Web API :

  • The Web API implements the OData (Open Data Protocol), version 4.0.
  • The new Web API provides better capabilities over the OData service introduced with CRM 2011 and OData service will be deprecating with this release.
  • It provides a modern, RESTful web service you can use to interact with data in CRM using a wide variety of platforms, programming languages and devices
  • The Web API will provide parity with the existing organization service (SOAP endpoint).
  • You can perform all operations using HTTP requests with the Web API located at [organization uri]/api/data/v8.0/

Impersonate another User using Web API:

  • To impersonate a user, add a request header named MSCRMCallerID with a GUID value equal to the impersonated user’s systemuserid before sending the request to the web service.

Sample Script with impersonation to create an Account Record

function createAccount() {
var clientURL = Xrm.Page.context.getClientUrl();
var impersonateUserId = “7eb682f1-ca75-e511-80d4-00155d2a68d1”;// GUID
var req = new XMLHttpRequest()
req.open(“POST”, encodeURI(clientURL + “/api/data/v8.0/accounts”), true);
req.setRequestHeader(“Accept”, “application/json”);
req.setRequestHeader(“Content-Type”, “application/json; charset=utf-8”);
req.setRequestHeader(“OData-MaxVersion”, “4.0”);
req.setRequestHeader(“OData-Version”, “4.0”);
// Set the Caller ID; GUID of User
req.setRequestHeader(“MSCRMCallerID”, impersonateUserId);
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
req.onreadystatechange = null;
if (this.status == 204) {
var accountUri = this.getResponseHeader(“OData-EntityId”);
alert(“New account created; URI: ” + accountUri)
}
else {
var error = JSON.parse(this.response).error;
alert(“Error creating Account – ” + error.message);
}
}
};

// Set Account record properties
req.send(JSON.stringify({ name: “Rajeev Pentyala”, description: “Account created using Web API”, revenue: 5000000 }));
}

🙂

Categories: CRM, CRM 2016 Tags: , ,