Featured Post

Web API Requests Series

Web API Series:  Create and Retrieve , Update and Delete , Retrieve Multiple , Associate/Disassociate , Impersonation , Run Workflows

04 March 2016

CRM 2016 - WEB API CRUD Operations - Impersonate another User

Web API series Part 1, Part 2, Part 3
Impersonating another user is very simple, you just need to set the XMLHttpRequest header as shown below.
Here are a couple of basic examples on how to impersonate a User in CRUD operations with the new CRM 2016 Web API in Javascript, here I am just going to show you impersonation in Create and Update. Impersonating another user should also be possible in Delete and Retrieve operations. I haven't tried it yet.

updateRecordOnBehalfOf = function (id, object, entitySetName, successCallback, errorCallback, impersonatedUserId) {

        var req = new XMLHttpRequest();
        req.open("PATCH", encodeURI(getWebAPIPath() + entitySetName + "(" + id + ")"), true);
        req.setRequestHeader("MSCRMCallerID", impersonatedUserId);
        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");
        req.onreadystatechange = function () {
            if (this.readyState == 4 /* complete */) {
                req.onreadystatechange = null;
                if (this.status == 204 || this.status == 1223) {
                    successCallback();
                }
                else {
                    errorCallback(bd_Utilities.WebAPI.errorHandler(this));
                }
            }
        };
        req.send(JSON.stringify(object));
    };

createOnBehalfOf = function (entitySetName, entity, successCallback, errorCallback, impersonatedUserId) {
        var req = new XMLHttpRequest();
        req.open("POST", encodeURI(getWebAPIPath() + entitySetName), true);      
        req.setRequestHeader("MSCRMCallerID", impersonatedUserId);
        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");
        req.onreadystatechange = function () {
            if (this.readyState == 4 /* complete */) {
                req.onreadystatechange = null;
                if (this.status == 204) {
                    if (successCallback)
                        successCallback(this.getResponseHeader("OData-EntityId"));
                }
                else {
                    if (errorCallback)
                        errorCallback(bd_Utilities.WebAPI.errorHandler(this.response));
                }
            }
        };
        req.send(JSON.stringify(entity));
    };

I hope this help you getting started with the new CRM 2016 Web API.

No comments:

Post a Comment