User Impersonation Using Web API

In this article we are going to provide sample code for impersonating users using Web API in Dynamics CRM 2016. Impersonation is a process where user A can execute some business logic on behalf of user B. To use impersonation both user should have privileges to perform the action. For example if user A wants to impersonate user B while creating account entity record, both user A and B should have create privileges on account entity. Also in addition to create privilege user A should have Act on Behalf of Another User privileges that can be set from Miscellaneous Privileges under Business Management tab in security role.
 
 
 
 
To impersonate user using Web API, we can set request header like below:
  1. request.setRequestHeader("MSCRMCallerID", <<GUID of the impersonated user>>);  
Here is the complete code to impersonate a user using Web API, we are impersonating auser while creating account entity record:
  1. function createAccount() {  
  2.     var ImpersonatedUserID = "1F7709D9-B31E-E611-80EC-4346BDDA181";//replace GUID here  
  3.     var serverURL = Xrm.Page.context.getClientUrl();  
  4.     var account = {};  
  5.     account["name"] = "Web API Impersonation Example";  
  6.    
  7.     var req = new XMLHttpRequest();  
  8.     req.open("POST", serverURL + "/api/data/v8.0/accounts"false);  
  9.     req.setRequestHeader("Accept""application/json");  
  10.     req.setRequestHeader("Content-Type""application/json; charset=utf-8");  
  11.     req.setRequestHeader("OData-MaxVersion""4.0");  
  12.     req.setRequestHeader("OData-Version""4.0");  
  13.     req.setRequestHeader("MSCRMCallerID", ImpersonatedUserID);  
  14.     req.onreadystatechange = function() {  
  15.         if (this.readyState == 4 /* complete */ ) {  
  16.             req.onreadystatechange = null;  
  17.             if (this.status == 204) {  
  18.                 var accountUri = this.getResponseHeader("OData-EntityId");  
  19.                 var ID = accountUri.substr(accountUri.length - 38).substring(1, 37); //get only GUID  
  20.                 Xrm.Utility.openEntityForm("account", ID); //Open newly created account record  
  21.             } else {  
  22.                 var error = JSON.parse(this.response).error;  
  23.                 alert(error.message);  
  24.             }  
  25.         }  
  26.     };  
  27.     req.send(JSON.stringify(account));  
  28. }  
Stay tuned for more updates ! 


Similar Articles
HIMBAP
We are expert in Microsoft Power Platform.