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?