Saturday, January 24, 2015

Web API with Windows Authentication

If you want to secure your ASP.NET Web API application with Windows Authentication, you simply have to add the [Authorize] attribute on all of your Web API Controllers, or else you can add the following code to your WebApiConfig.cs class:
 
config.Filters.Add(new AuthorizeAttribute());



However, if you want to pass Windows Authentication credentials from your .NET Client to Web API, you will need to do something like what is outlined in the following article:  http://www.asp.net/web-api/overview/security/integrated-windows-authentication

Of course, this does not provide any guidance on passing Windows Authentication credentials from a Web Application such as an ASP.NET MVC Client.

Fortunately, there is a way to accomplish this even from ASP.NET MVC though it is not readily obvious:




  1. First, set up your ASP.NET MVC Web Application for Windows Authentication
  2. Add an Identity Impersonation element to your Web.config
  3. In IIS, set up your ASP.NET MVC Web Application as well as your ASP.NET Web API Web Application to run in Classic Mode (rather than Integrated mode)
  4. Now when you run your code where you call your Web API Service from your ASP.NET MVC Controller, the Windows Authentication credentials will pass seamlessly between each other!

To set up identity impersonation in your Web.config file, you need to the add the following entry:



<identity impersonate="true"/>
If you forget to set your Application Pools from Integrated Mode to Classic Mode, you will get an error similar to the following:







The code to call your Web API Service from an ASP.NET MVC Controller will look like the following:



public ActionResult Index()
        {
            string webApiUrl = "http://localhost/WebAPI/";
 
            HttpClientHandler handler = new HttpClientHandler()
            {
                UseDefaultCredentials = true
            };
 
            HttpClient client = new HttpClient(handler);
 
            client.BaseAddress = new Uri(webApiUrl);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
 
            // HTTP GET
            HttpResponseMessage response = client.GetAsync("api/values").Result;
 
            if (response.IsSuccessStatusCode)
            {
                var model = response.Content.ReadAsStringAsync().Result;
                ViewBag.Message = model.ToString();
            }//if
 
 
            return View();
        }

No comments:

Post a Comment