Impersonation in CRM Plug-In and Workflow – the easy way

Some time ago I wrote a post about impersonation in dynamics crm plug-ins.

Today I found a much easier solution: use the impersonated organizationService from localcontext.

IOrganizationService service = localContext.OrganizationServiceImpersonated;

Ok, first you have to create this property. Do this in Plugin.cs, which gets generated by Visual Studio. Create the property:

internal IOrganizationService OrganizationServiceImpersonated
{
    get;
    private set;
}

Add the following line to the constructor of LocalPluginContext:

// Use the factory to generate the impersonated Organization Service.
this.OrganizationServiceImpersonated = factory.CreateOrganizationService(null);

Instead of null you can also pass a systemusers GUID. Null will impersonate as systemadministrator.

And when you are just there, also set the ServiceProvider correctly, so that it’s not null. Then the whole constructor looks like this:

internal LocalPluginContext(IServiceProvider serviceProvider)
{
    if (serviceProvider == null)
    {
        throw new ArgumentNullException("serviceProvider");
    }

    // 1. extra line: Set LocalContext ServiceProvider
    this.ServiceProvider = serviceProvider;

    // Obtain the execution context service from the service provider.
    this.PluginExecutionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

    // Obtain the tracing service from the service provider.
    this.TracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

    // Obtain the Organization Service factory service from the service provider
    IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

    // Use the factory to generate the Organization Service.
    this.OrganizationService = factory.CreateOrganizationService(this.PluginExecutionContext.UserId);

    // 2. extra line: Use the factory to generate the impersonated Organization Service.
    this.OrganizationServiceImpersonated = factory.CreateOrganizationService(null);
}

To get impersonated service in Workflows is a little easier:

var serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
var service = serviceFactory.CreateOrganizationService(null);      //Create impersonated service