简体   繁体   中英

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

  • First with proxy.
  • Second with API base 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?

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;

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

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