How to use credentials in HttpClient in c#?
Asked Answered
M

3

23

I am facing some problems when using the HttpClient class to access to a Delicious API. I have the following code:

try
{
    const string uriSources = "https://api.del.icio.us/v1/tags/bundles/all?private={myKey}";
    using (var handler = new HttpClientHandler { Credentials = new  
                             NetworkCredential("MyUSER", "MyPASS") })
    {
         using (var client = new HttpClient(handler))
         {
             var result = await client.GetStringAsync(uriSources);
         }
   }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "ERROR...", MessageBoxButton.OK);
}

When running the code above I am getting the following: Response status code does not indicate success: 401 (Unauthorized).

So, how could I get this work? Is it possible?

Thanks in advance

Regards!

Meltwater answered 28/8, 2013 at 2:36 Comment(9)
401 Unauthorized means Incorrect User Name or Password...Rawson
I know, however I am using the correct ones ;-)Meltwater
When I put the above url in any browser it ask me for the credencial (the same I am using in the code) and it works. So, I guess it is related the way how the httpClient is requesting the dataMeltwater
This may seem a silly question, but you are actually using your private key instead of {myKey} and youve just put that in there for the purpose of demonstration right?Forestry
That's right. I put it just for demostration purpose as well as the user name and password. I am using the good ones in my sandbox ;-)Meltwater
Is it possible that you need to specify a domain for your network credentials? Thats the only thing I can think of for an authorize error when your login details are correct :(Forestry
Maybe strange to reply that but... sometimes I've that kind of behavior and in fact I lost the Internet connection in my WP emulator. Try to launch IE.Plenty
Have you tried using HttpWebRequest, blog.karlbunyan.com/2007/02/11/…Expressly
Hi Erwin. I haven't had the time to test your suggestion until now. and it works OK for me. The only concern is that the HttpWebRequest is executed in the same thread of the UI. But, I only need it to retrieve a few data. So, I guess this will be Ok. Thanks ;-)Meltwater
V
35

I had the exact same problem myself. It seems the HttpClient just disregards the credentials set in the HttpClientHandler.

The following shall work however:

using System.Net.Http.Headers; // For AuthenticationHeaderValue

const string uri = "https://example.com/path?params=1";
using (var client = new HttpClient()) {
    var byteArray = Encoding.ASCII.GetBytes("MyUSER:MyPASS");
    var header = new AuthenticationHeaderValue(
               "Basic", Convert.ToBase64String(byteArray));
    client.DefaultRequestHeaders.Authorization = header;

    var result = await client.GetStringAsync(uri);
}

No need for the handler.

Source: http://www.snip2code.com/Snippet/13895/Simple-C---NET-4-5-HTTPClient-Request-Us

Viminal answered 28/5, 2014 at 14:37 Comment(2)
This solution works well as it allows for the Authorization header to be set on the first request, thus bypassing the 401 Challenge / Response. In my experience with HttpClient and the HttpClientHandler, however, setting pre-authenticate does work in that the Authorize header is set on every request after the 401 Challenge / Response is completed. This article here explains it well: weblog.west-wind.com/posts/2010/Feb/18/…Chyou
@Adam Szabo this seems the original sourceSignature
O
2

This is an old post but thought to add my reply for someone facing similar issue and browsing answers...

I faced similar issue. In my case, setting Domain property for NetworkCredentials worked. You can try setting Domain.

Open answered 5/10, 2015 at 12:8 Comment(0)
B
0

The code you are showing works for me against an authenticated resource. I suspect Delicious is doing something weird.

Considering you are on Windows Phone, it is a pain to debug with Fiddler, so what I suggest is getting a Runscope account. Install this message handler which will redirect your request via the RunScope debugger. Once you do this, I suggest you look at the www-authenticate header and examine what that is returning.

If all else fails you can always set the Authentication header directly with basic auth credentials. You don't need to use the Credentials class.

Byran answered 31/8, 2013 at 16:7 Comment(1)
I have a similar issue posted here in case you get a chance for a suggestion/your thoughts etc.Mitchiner

© 2022 - 2024 — McMap. All rights reserved.