Reputation: 3178
I'm getting a 401 error whenever I attempt to get a response from HttpClient when I turn off Anonymous Authentication.
StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1,
Content: System.Net.Http.StreamContent, Headers:
{
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcUGFycmlzaFxEb2N1bWVudHNcJ0xSXFNvdXJjZVxBcHBzXExSUiBBRkVcTFJSX0FGLVxhcGlcYWZlXDg0QTk0NjVFQzg2QTQwQjNBNEJCNkJDOTI3MTFGRjNB?=
Cache-Control: private
Server: Microsoft-IIS/10.0
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
X-Powered-By: ASP.NET
Date: Mon, 27 Aug 2018 18:14:05 GMT
Content-Length: 6166
Content-Type: text/html; charset=utf-8
}
For testing I have the controller Authenticating on a single user.
[Authorize(Users = @"Domain\Username")]
public class ExampleController : Controller
{
public async Task<ActionResult> Index(string exampleId)
{
var baseUrl = $"{Request.Url.Scheme}://{Request.Url.Authority}{Url.Content("~")}";
var client = new HttpClient(); // <-- This is WRONG*
var response = await client.GetAsync($"{baseUrl}api/example/{exampleId}");
var example = await response.Content.ReadAsAsync<ExampleModel>();
return View(example);
}
}
I've looked into using HttpClient.DefaultRequestHeaders.Authentication
, but I don't see a way to get it to work with ActiveDirectory. I've looked here but can't understand where I'd be getting an authorization token in this case.
If I create a new controller manually and invoke it directly instead of through the API this works, but it really isn't authenticating anything in that case right?
*Edit:
As ADyson points out, my error was not initializing the HttpClient correctly. Here is how it should have been written:
var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
Upvotes: 1
Views: 1202
Reputation: 61784
You need to set UseDefaultCredentials = true
(in an instance of HttpClientHandler
, which you pass to the HttpClient
).
Upvotes: 2