1

I've built an ASP.NET MVC 4 website with an ASP.NET Web Api which is to be secured with Windows authentication in IIS. Things work fine when in Visual Studio; the calls of HttpClient are working and always return the data along with status code 200. However, when I publish to IIS, that's where things go wrong; when trying to make a call to the api, I always get a 401 Unauthorized with these settings:

Authentication: Windows Authentication only Authorization: Allow only one user - me.

However, when I change Authorization to Allow All, it works fine, but that is not the behavior I want.

I tried calling the API directly from the browser with authorization only set to my account...and it works fine like a good little Api; no unauthorized error unless I logon as a different user.

So I guess this leads me to conclude that something's wrong with how the website communicates with the API. Here's my code for that:

public ActionResult Index()
{
    HttpClientHandler handler = new HttpClientHandler();
    handler.UseDefaultCredentials = true;

    using (HttpClient client = new HttpClient(handler))
    {
        var clientResult = client.GetAsync(
        string.Format(@"{0}{1}",ConfigurationManager.AppSettings["WebApiBaseUri"].ToString(), "products")
        ).Result;
        clientResult.EnsureSuccessStatusCode();
        //if (clientResult.StatusCode != HttpStatusCode.OK)
        //{
        //    ViewBag.Error = clientResult.StatusCode;
        //    ViewBag.User = userName;
        //    ViewBag.Message = clientResult.Content.ReadAsStringAsync().Result;
        //    return View();
        //}

        var receivedData = clientResult.Content.ReadAsStringAsync().Result;
        List<ProductModel> data = JsonConvert.DeserializeObject<List<ProductModel>>(receivedData);
        return View(data);
    }
}

and here's the code on the API side:

public IQueryable<Product> Get()
{
    _context = new InventoryContext();
    return _context.Products.AsQueryable();
}

Anyone know what I'm doing wrong?

ekad
  • 14,436
  • 26
  • 44
  • 46
Paco G
  • 391
  • 1
  • 3
  • 15

1 Answers1

0

The problem is that you are assuming that the IIS process running the HttpClient request will send over the credentials of the user who made the request to the website. That's not true unless you set up Kerberos to pass credentials along. Instead, the default credentials will send over the credentials of the user that the application pool in IIS is set to run under. There's a much more detailed answer to this question in another question, along with some directions on how to get going with Kerberos: ASP.NET passing along Windows Authentication credentials. If you added the account your IIS process is running under to your authorization list you should see your call succeed, though I'm guessing that's not how you want this to work.

Community
  • 1
  • 1