sansalk
sansalk

Reputation: 4741

How do I use HttpClient for Basic authentication & API Key header together

I have tried the same with HttpWebRequest its working fine but I need to use HttpClient for my program So far I did following code but its returning unauthorised

        string baseurl = "http://xxxxx.net/";
        var byteArray = Encoding.ASCII.GetBytes("myusername:mypassword");
        webclient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
        webclient.DefaultRequestHeaders.Authorization =  new AuthenticationHeaderValue("X-ApiKey", "=" + "5AB4374B-A5CF-4F7A-91FF-E5E893347C3F");
        webclient.BaseAddress = new Uri(baseurl);
        webclient.DefaultRequestHeaders.Clear();
        webclient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

Upvotes: 0

Views: 13677

Answers (2)

sansalk
sansalk

Reputation: 4741

Still, I get the Unauthorized error but web request working fine

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";
            httpWebRequest.Headers["X-ApiKey"] = "5AB4374B-A5CF-4F7A-91FF-E5E893347C3F";
            String encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes("myusername" + ":" + "mypassword"));
            httpWebRequest.Headers.Add("Authorization", "Basic " + encoded);

Upvotes: 0

Gabriel Luci
Gabriel Luci

Reputation: 40938

The problem is here:

webclient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
webclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("X-ApiKey", "=" + "5AB4374B-A5CF-4F7A-91FF-E5E893347C3F");

The second one is overwriting the first, so the Basic authentication isn't happening. If you want to include an X-ApiKey header in the request as well as using Basic auth, then don't use DefaultRequestHeaders.Authorization to set the X-ApiKey header. Instead use DefaultRequestHeaders.Add, which lets you add any HTTP header you want:

webclient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
webclient.DefaultRequestHeaders.Add("X-ApiKey", "5AB4374B-A5CF-4F7A-91FF-E5E893347C3F");

I removed the "=" + from the code since the = is added automatically. But if the = is actually part of your API key, then add it back.

Upvotes: 6

Related Questions