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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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:
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:
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:
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:
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0



