Search code examples
c#asp.netasp.net-mvcwcfservice

How do I fetch the domain\username from a WCF service call made from MVC application?


I have an ASP.NET service hosted on IIS running the App pool with a service account. I need to fetch the username and domain of the user calling the service from an MVC controller. How can I fetch the required details? The details need to fetched in service and not sent from MVC application. I have tried using WindowsIdentity.GetCurrent().Name but it gives me the service account details.


Solution

  • You can try to use HttpContext.Current.User.Identity.Name and need to enable windows authentication in IIS:

    HttpContext.Current.User.Identity.Name
    

    Getting A Users Username in ASP.NET:

    Scenario 1: Anonymous Authentication in IIS with impersonation off:

    enter image description here

    As you can see where we’re running with Anonymous Authentication HttpContext.Current.Request.LogonUserIdentity is the anonymous guest user defined in IIS (IUSR_COMPUTER1 in this example) and as the user is not authenticated the WindowsIdentity is set to that of the running process (ASPNET), and the HttpContext.Current.User.Identity is not set.

    Scenario 2: Windows Authentication in IIS, impersonation off:

    enter image description here

    Using Windows Authentication however enables the remote user to be authenticated (i.e. IsAuthenticated is true) automatically via their domain account and therefore the HttpContext.Current.Request user is set to that of the remote clients user account, including the Identity object.

    Scenario 3: Anonymous Authentication in IIS, impersonation on:

    enter image description here

    This time we’re using Anonymous Authentication but now with ASP.net Impersonation turned on in web.config. The only difference to the first scenario is that now the anonymous guest user IUSR_COMPUTER1 is being impersonated and therefore the System.Environment and Security.Principle are using running under that account’s privileges.

    Scenario 4: Windows Authentication in IIS, impersonation on:

    enter image description here

    Now with Windows Authentication and Impersonation on everything is running as our calling user’s domain account. This means that the ASP.net worker process will share the privileges of that user.