Redigera

Dela via


Impersonate a user

Sometimes you need the code in a plug-in to run in the context of a different user, for example to perform an operation on their behalf.

There are two ways to apply impersonation in plug-ins: at registration or execution.

At plug-in registration

When you register a plug-in step you can specify a user account to use when the code is run by choosing from the Run in User's Context option. By default this is set to use the Calling User, which is the user account which initiated the action. When this default option is applied, the SdkMessageProcessingStep.ImpersonatingUserId will be set to null or Empty.

More information: Register plug-in step

During plug-in execution

You can override the setting specified at registration at run time by setting the IOrganizationServiceFactory.CreateOrganizationService(Nullable<Guid>) userId parameter.

This is typically set to the IExecutionContext.UserId value which will apply the user account defined by the plug-in step registration.

(IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

If you want to override the step registration you can pass the value of the IExecutionContext.InitiatingUserId to have a service that will use the user account that initiated the action that caused the plug-in to run.

You can also provide the SystemUser.SystemUserId from any valid user account. This will work as long as that user has the permissions to perform the operations in the plug-in.

See also

Plug-ins
Write a plug-in