Windows authentication and Asp.Net Web API

agez picture agez · Feb 14, 2013 · Viewed 10.9k times · Source

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?

Answer

Mark Jones picture Mark Jones · Feb 14, 2013

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.