Impersonation of Service Executions in Plug-Ins and Workflows

A service execution can be impersonated by instantiating a ServiceProxy an setting the CallerId.
The Plug-In (and maybe Workflow) has to be registered as full trust (IsolationMode=”None”) to use the DefaultNetworkCredentials, otherwise they will be null. Set the isolationmode in registerfile.
If you use Early Binding, don’t forget to enable proxy types by calling serviceProxy.EnableProxyTypes().

protected void ExecutePreAccountUpdate(LocalPluginContext localContext)
{
    if (localContext == null)
    {
        throw new ArgumentNullException("localContext");
    }

    IPluginExecutionContext context = localContext.PluginExecutionContext;

    var clientCredentials = new ClientCredentials();
    // Using custom credentials
    credentials.Windows.ClientCredential = new NetworkCredential(, , );

    // Using Default Credentials
    // credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;

    var orgUrl = "http:///XRMServices/2011/Organization.svc";
    var organizationServiceUri = new Uri(orgUrl);

    // To use SSL
    if (!string.IsNullOrEmpty(orgUrl) && orgUrl.Contains("https")) {
	ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
    }

    using (var serviceProxy = new OrganizationServiceProxy(organizationServiceUri, null, clientCredentials, null))
    {
        serviceProxy.EnableProxyTypes();
        serviceProxy.CallerId = new Guid("AAB4EBA7-BDD1-E211-A6C5-00155D0B2738");    //Impersonating serviceProxy

        var newTask = new Task();
        newTask.Description = "ServiceProxy created Task";
        newTask.Subject = "ServiceProxy created";

        var newTaskGuid = serviceProxy.Create(newTask);
    }
}

Blog post about the different userIds, when impersonating Plug-Ins, Dialogs and Workflows: https://community.dynamics.com/crm/b/develop1/archive/2013/08/09/user-impersonation-in-plugins-workflow-and-dialogs.aspx

Leave a Reply

Your email address will not be published. Required fields are marked *