I have an Intranet application with Windows authentication based on MVC4.
When I need the WindowsIdentity for authorization purpose in a Controller I just use
HttpContext.User.Identity
Now I wanted to use the new Asp.Net WebAPI for some Ajax calls.
Is there a way to get the WindowsIdenty object in the same easy way as in an MVC Controller?
Windows authentication enables users to log in with their Windows credentials, using Kerberos or NTLM. The client sends credentials in the Authorization header. Windows authentication is best suited for an intranet environment.
On the taskbar, click Start, and then click Control Panel. In Control Panel, click Programs and Features, and then click Turn Windows Features on or off. Expand Internet Information Services, then World Wide Web Services, then Security. Select Windows Authentication, and then click OK.
The ASP.NET Web API Framework provides a built-in authorization filter attribute i.e. AuthorizeAttribute and you can use this built-in filter attribute to checks whether the user is authenticated or not. If not, then it simply returns the HTTP status code 401 Unauthorized, without invoking the controller action method.
Please don't reference the HttpContext
from a controller.
You can access the Controllers User
property which is way of accessing the Identity through without a dirrect reference to HttpContext
.
public class MyController : ApiController
{
public string Get()
{
var indenty = this.User.Identity;
}
}
Why
The controllers User
property provides a level of abstraction which allows for easier mocking and thus unit testing. This abstraction also allows for greater portability e.g. if this was WebApi Self Host you wouldn't even have access to HttpContext
.
To read more about how to unit test and mock the User property read here. For more information re: portability read here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With