Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows authentication and Asp.Net Web API

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?

like image 894
agez Avatar asked Feb 14 '13 11:02

agez


People also ask

Can we use Windows authentication in Web API?

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.

How do I use Windows authentication on a web application?

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.

How do I use authentication and authorization in Web API?

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.


1 Answers

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.

like image 66
Mark Jones Avatar answered Oct 22 '22 21:10

Mark Jones