I'm working on setting up permissions for my Web API 2 and I've ran into an issue that I've been looking at for quite some time.
When I run my application locally I am unable to get the current user name on my ApiController
by using the IPrincipal.User
method. What I want to do with this is to search for the user within my AD and then filter the groups returned to determine if the user has access to certain access to different web pages.
To overcome not being able to get the current user using the IPrincipal
class I have used the HttpContext.Current.Request.LogonUserIdentity.Name;
. This works but I can't understand why I can't use the IPrincipal
class to achieve the same out.
Foot note:
Do I need to configure my ApiController in a certain way for the User to return from the IPrincipal
class?
In Web.Config file I have set the following authentication mode:
<authentication mode="Windows" />
So I was able to fix the issue and it was one that was helped by using the following website:
Basically I had to access the hidden .vs folder from my project location. Within there I went to config and then edited the applicationhost
file. I then applied the following to the end of the config file:
<location path="AccidentReporting.Web">
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="false" />
<windowsAuthentication enabled="true" />
</authentication>
</security>
</system.webServer>
</location>
<location path="AccidentReporting.API">
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="false" />
<windowsAuthentication enabled="true" />
</authentication>
</security>
</system.webServer>
</location>
You can see I've added the location proper twice and that's because within my solution I've two projects, one for hosting the API and the other for hosting the WEB application.
So now within my API Controller
I an access the user identity name by using the User.Identity.Name
method.