2
votes

I've looked at a lot of questions addressing this issue and nothing seems to work. I'm trying to call a web api service from an mvc web application. This is my client code:

var client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true })
{
    BaseAddress = baseAddress
};
var response = await client.GetAsync("items/5");

When I run it locally, it works. When I publish the project to the server the api always returns 401 Unauthorized. I have enabled windows authentication on the web api and mvc project in IIS. How do I get the correct windows credentials to the api from the mvc application? The web api and mvc app are running on the same IIS server.

2
In what context is this application code running? Another Web App? Console App? That is where you are going to setup the correct authentication.Cam Bruce
@CamBruce this client code is being run by the mvc web appEric B

2 Answers

3
votes

If, by chance, the MVC app can make all requests to the WebAPI using the same Windows credentials, then I think you should be able to just configure IIS's application pool to run as a domain user. By default IIS's app pools run as some machine local account. So, if it tries to make a request over the network to a Windows Authenticated resource, the remote machine doesn't recognise the web server's machine local account. Hence the unauthorised error.

However, if you want to get the MVC app to call the WebAPI as the user who made the request to the MVC app, then you'll need to turn on impersonation in web.config. You'll probably also need to get your domain admin to turn on Kerberos delegation for your web server machine, due to the way that Kerberos/Active Directory works (look up kerberos double hop).

0
votes

The problem was that apparently if you try to send a request to the same machine using a fully qualified domain name, the request will automatically fail to protect against a reflection attack.

I fixed this by changing baseAddress from

http://example.com/api

to

http://localhost/api