MuhammadElshater
MuhammadElshater

Reputation: 49

C# .. API httpclient authentication and proxy with username and password

I'm new in API's world but I had a question, I want to get data from Web API but there's two authentication

here's my Get Action code:

        HttpClientHandler handler = new HttpClientHandler();
        handler.Credentials = new NetworkCredential("test", "testing");
        HttpClient client = new HttpClient(handler);
        client.BaseAddress = new Uri("http://test.abctesting.com/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.
            MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = client.GetAsync("admin/apiv2/").Result;
        var tenders = response.Content.ReadAsAsync<tenders>().Result;

this code work fine with me but just in pass over proxy username and password! How can I continue to Get API Data with authentication username and password?

Upvotes: 3

Views: 10766

Answers (2)

Jaya
Jaya

Reputation: 3921

Since you mentioned "Basic Auth" on comments adding the following lines in addition to what you have might help

 var byteArray = Encoding.ASCII.GetBytes($"{yourUsername}:{yourPassword}");
 client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

Although there are other popular modes of auth such as OAuth, Bearer etc. Change the key on AuthenticationHeaderValue according to the mode of authentication and set the value appropriately

Upvotes: 6

Rodrigo Vedovato
Rodrigo Vedovato

Reputation: 1008

This should work:

HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential("test", "testing");
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("http://test.abctesting.com/");
client.DefaultRequestHeaders.Accept.Clear();

client.DefaultRequestHeaders.Accept.Add(
    new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

string user = "user", password = "password";

string userAndPasswordToken =
    Convert.ToBase64String(Encoding.UTF8.GetBytes(user + ":" + password));

client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", 
    $"Basic {userAndPasswordToken}");

HttpResponseMessage response = client.GetAsync("admin/apiv2/").Result;
var tenders = response.Content.ReadAsAsync<tenders>().Result;

Upvotes: 1

Related Questions