Impersonation available using WEB API in Dynamics CRM 2016

By | February 26, 2016

Introduction:

Microsoft Dynamics CRM online 2016 update and Dynamics CRM 2016 (on-premises) has introduced a new concept called the Web API. This can be used across a wide variety of programming languages, platforms, and devices. One of the features of Web API is Impersonation.

Back in the days of CRM 4, Impersonation through scripting was supported by including the impersonation details in the header of the SOAP request.

Later this feature was removed and there was no way to impersonate a user through Scripting.

Impersonation is used when you want to execute business logic (code) on behalf of another CRM user. This is necessary because the CRM Web services can be called by various clients and services on behalf of a CRM user. Impersonation involves two different users where User (X) is used for executing the code to perform some tasks on behalf of another user (Y).

Walkthrough of Impersonation through Script

The User account (X) has to be given the prvActOnBehalfOfAnotherUser privilege to perform the task.

In order to impersonate a user through the Web API, you need to add ‘MSCRMCallerID’ key with GUID of the impersonated user. In the below example, a new contact entity is created on behalf of the user with systemuserid B65AB846-7EBE-E511-80DF-00155D06F307.

Here’s the code which helps you to impersonate a user through the Web API.

function impersonateUserReq()
{
    var userID = null;

    try {

        // create the contact object
        var contact = new Object();
        contact.firstname = "FirstName";
        contact.lastname = "LastName";
        contact.accountrolecode = 2;
        contact.creditonhold = false;
        contact["parentcustomerid_account@odata.bind"] = "/accounts(89C202DF-B1AF-E511-80E9-00155D06D000)"

        ///set the impersonateUser userid -  
        userID = "B65AB846-7EBE-E511-80DF-00155D06F307";

        Inogic.ApiLib.impersonateUser("contacts", contact, userID,
           impersonateUserSuccess,
           impersonateUserError);
    } catch (e) {
        showMessage(e.message);
    }
}
      // this Actual ajax request function is used to create the record and impersonate the user
            impersonateUser: function (entitySetName, entity,userId, successCallback, errorCallback) {

                var jsonEntity = null;

                try {

                    //create json object
                    var jsonEntity = window.JSON.stringify(entity);

                    //create AJAX request
                    $.ajax({
                        type: "POST",                      
                        contentType: "application/json; charset=utf-8",
                        datatype: "json",
                        url: encodeURI(this.getWebAPIPath() + entitySetName),
                        data: jsonEntity,
                        beforeSend: function (xhr) {
                            //Specifying this header ensures that the results will be returned as JSON.            
                        
                            xhr.setRequestHeader("MSCRMCallerID", userId);
                            xhr.setRequestHeader("Accept", "application/json");
                            xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                            xhr.setRequestHeader("OData-MaxVersion", "4.0");
                            xhr.setRequestHeader("OData-Version", "4.0");
                        },
                        success: function (data, textStatus, xhr) {

                            //call successCallback
                            successCallback(xhr.getResponseHeader("OData-EntityId"));
                        },
                        error: function (xhr, textStatus, errorThrown) {
                            errorCallback(Inogic.ApiLib.errorHandler(xhr));
                        }
                    });
                } catch (e) {
                    throw new Error(e);
                }
            },

In the above code, the only addition is the following line of code

   xhr.setRequestHeader("MSCRMCallerID", userId);

Once the callerid is set, the record is created using the privileges that is assigned to the user specified in the callerid rather than the logged in user.

Conclusion:

On a concluding note, impersonation helps to perform operations on behalf of other users if the system account running the code has the necessary privileges.

You may also like to read : Make your Dynamics CRM life easy with Inogic Dynamics CRM Solutions.