简体   繁体   中英

Authorizing AD Group\User With HttpClient

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 }); 

您需要设置UseDefaultCredentials = true (在HttpClientHandler的实例中,您将其传递给HttpClient )。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM