Archive
CRM 2016 Web API – Impersonate User
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 }));
}
🙂
UserId & InitiatingUserId properties in Plugin of CRM
In CRM plugin, “IExecutionContext” contains 2 properties
- UserId
- Gets the GUID of the user for whom the plug-in invokes “on behalf of”.
- InitiatingUserId
- Gets the GUID of the user under which the current pipeline is executing.
Consider a scenario
- You have a user “RAJ” with “Sales Person” role with only “User Level” “Read” privilege on ‘Contact’
- You have a plugin on Post Deletion of ‘Contact’ with name “PostContactDelete”
- Assume in one particular scenario user “RAJ” should be able to delete a ‘Contact’
- So you can run the “PostContactDelete” plugin in the user with “SystemAdministrator” role
- (i.e., Set “Run in User’s Context” to User with admin role; In sample screen shot below I chosen my admin user whose name is ‘CRM WaSu1)
- When User “RAJ” logs in and try to delete ‘Contact’ the plug-in “PostContactDelete” fires. When you debug
- IExecutionContext.UserId = GUID of SystemAdministrator (i.e., OnBehalfOf User ‘RAJ’)
- IExecutionContext. InitiatingUserId =GUID of RAJ (i.e., Actual User)
🙂
Creating OrganizationServiceProxy in CRM2011 custom applications
Hi,
Below are the steps to instantiate “Organization Service Proxy” which can be used to consume CRM service and perform operations in a custom application
– Refer “Microsoft.Xrm.Sdk & Microsoft.Xrm.Sdk.Client” .dll’s to your custom application
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using System.Net.Security;
using System.ServiceModel.Description;
using System.Security.Cryptography.X509Certificates;
private Uri homeRealmUri = null;
private ClientCredentials credentials;
private Uri organizationUri;
private IOrganizationService service;
private OrganizationServiceProxy serviceProxy;
credentials = new ClientCredentials();
// If CRM On-Premise
// To use custom credentials pass user credentials
credentials.Windows.ClientCredential = new NetworkCredential( {userId},{ password},{ domain} );
// To use Default Credentials; Uncomment below line and comment above
// credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
// If CRM Online
credentials.UserName.UserName = “Office 365 ID”; // i.e., name@domain.onmicrosoft.com
credentials.UserName.Password = “Office 365 Password”;
// Use “https” if CRM is SSL configured
string orgUrl= “http://ServerName/OrganizationName/XRMServices/2011/Organization.svc”;
// Add this line if URL has “https” (i.e.,CRM is SSL configured)
if (!string.IsNullOrEmpty(orgUrl) && orgUrl.Contains(“https”)) {
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain,
SslPolicyErrors sslPolicyErrors) { return true; };}
organizationUri = new Uri(orgUrl);
using (
serviceProxy =
new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null))
{
// To impersonate set the GUID of CRM user here
serviceProxy.CallerId = {GUID of CRM User};
serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
service = serviceProxy;
}
Hope it helps 🙂