1

I'm working on a custom plug-in (non-sandboxed) in a CRM2016 on-prem to interface with an internal webAPI.

When I run this piece of code, it is returning the CRM App Pool user and not my user name:

(System.Security.Principal.WindowsIdentity)HttpContext.Current.User.Identity;

Is this expected and normal? If it is, how do you impersonate the calling user for external calls.

Thanks.

Dave S
  • 25
  • 6

1 Answers1

0

Yes that is normal, synchronous plugins run on the web server, so getting the IIS App Pool user is expected. If the plugin is running asynchronously its runs on the back end asynchronous service so you would probably get a different service account.

You could examine the plugin execution context (IPluginExecutionContext) to get eitherInitiatingUserId or UserId, which is the CRM GUID of the system user account under which the plugin is executing - depending how on the plugin is executed and registered this can give you the CRM identity of the user who started the plugin.

Jeff describes this within; How to get current user record in CRM plugin?

The information is available in the PluginExecutionContext. The code below is from the Execute method your plugin must implement.

public void Execute(IServiceProvider serviceProvider)
{
    IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
        IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
    Guid userId = context.InitiatingUserId;
}

FYI, the context also has a "UserId" property that may or may not be the same as the InitiatingUserId. If your plugin step registration "Run in Users's Context" field has the value "Calling User", then they will be the same. If you have specified a user in the "Run in User's Context" field, then the UserId field will contain the user ID of the person you specify and the InitiatingUserId will be the actual CRM user whose action triggered the plugin. Sounds like you're looking for the InitiatingUserId.

Or perhaps you could use another indicator, such as whoever last modified some record. You could then lookup their details in CRM, e.g. to get their domain name.

Depending on how you authenticate with the external service this might help to impersonate the user. Otherwise there as far as I know there is no easy way to get the users security token for example, CRM doesn't really expose that information.

Community
  • 1
  • 1
James Wood
  • 17,286
  • 4
  • 46
  • 89