0

Unable to use the System.Net API to authenticate current user to a REST endpoint. Example below returns 401 unauthorized

using (HttpClient client = new HttpClient())
{
    using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://rest/api/endpoint")
    {
        using (httpResponseMessage response = await client.SendAsync(request))
        {
            if (response.IsSuccessStatusCode)
                //do something
        }
    }
}

If I use NSUrlConnection I am able to authenticate not problem. So, NSUrlConnection must be passing the credentials some how. Below is a snippet of that code:

var request = new NSMutableUrlRequest(new NSUrl("http://rest/api/endpoint"), NSUrlRequestCachePolicy.ReloadIgnoringCacheData, 0);
request["Accept"] = "application/json";
NSUrlConnection.SendAsynchronousRequest(request, NSOperationQueue.MainQueue, delegate(NSUrlResponse, response, NSData data, NSError error)
{
    // successfully authenticated and do something with response
});

I would like to wrap my service code in a PCL to share with other platforms. Therefore, I would like to get this all working within the System.Net api. Is this possible?

UPDATE:
I've tried using an HttpClientHandler and using default credentials as well as CredentialCache.DefaultNetworkCredentials. The only way to get this to work is to hardcode the credentials, which I do not want. It appears the System.Net stack does not surface the credentials from the OS.

Paul
  • 1
  • 1
  • 1
    I assume you need to add a header for authorization, depends on the endpoint. Typing `c# httpclient authenticate` into your favourite search engine should have answered the question. – Equalsk Jan 25 '17 at 17:28
  • this only works if I send hard coded credentials along with the header. However, I want to use the current credentials of the user that is currently logged onto the mac. – Paul Jan 25 '17 at 17:44

1 Answers1

0

I assume it's using default authentication. You could do that with HttpClient with an HttpClientHandler, for example:

using (var handler = new HttpClientHandler {
    UseDefaultCredentials = true
})
using (var client = new HttpClient(handler))
{
    var result = await client.SendAsync(...);
}
Peter Ritchie
  • 35,463
  • 9
  • 80
  • 98
  • Hmm, this might be a limitation of HttpClient. http://stackoverflow.com/questions/12212116/how-to-get-httpclient-to-pass-credentials-along-with-the-request – Peter Ritchie Jan 25 '17 at 17:53