Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling WEB API with basic authentication in C#

I have a working WEB API that I wrote, and I added basic authentication to the API (username is "testing", password is "123456"). However, when trying to call that API from my web form, I keep getting the "(401) Unauthorized" message. What should I change in the web code to call the API successfully?

 string url = String.Format("http://example.com"); //here I have the correct url for my API
 HttpWebRequest requestObj = (HttpWebRequest)WebRequest.Create(url);
 requestObj.Method = "Get";
 requestObj.PreAuthenticate = true;
 requestObj.Credentials = new NetworkCredential("testing", "123456");
 HttpWebResponse responseObj = null;
 responseObj = (HttpWebResponse)requestObj.GetResponse();
 string strresult = null;
 using (Stream stream = responseObj.GetResponseStream())
 {
     StreamReader sr = new StreamReader(stream);
     strresult = sr.ReadToEnd();
     sr.Close();
 }

This is what my API searches for in terms of authentication:

actionContext.Request.Headers.Authorization.Parameter

Should I be adding a header instead of NetworkCredential or is it the same thing?

like image 206
Maya Berk Avatar asked Aug 26 '19 21:08

Maya Berk


People also ask

How do I use Basic Authentication in Web API?

In IIS Manager, go to Features View, select Authentication, and enable Basic authentication. In your Web API project, add the [Authorize] attribute for any controller actions that need authentication. A client authenticates itself by setting the Authorization header in the request.

How do I add basic auth to API?

OutSystems allows you to add basic authentication to the requests made to the REST APIs you are exposing. For that, do the following: In the Logic tab, open the Integrations folder. Select the exposed REST API you want to change and set its "Authentication" property to Basic .

How can I pass the basic HTTP authentication?

We can do HTTP basic authentication URL with @ in password. We have to pass the credentials appended with the URL. The username and password must be added with the format − https://username:password@URL.


Video Answer


1 Answers

This should help:

    HttpMessageHandler handler = new HttpClientHandler()
    {
    };
        
    var httpClient = new HttpClient(handler)
    {
         BaseAddress = new Uri(url),
         Timeout = new TimeSpan(0, 2, 0)
    };
        
    httpClient.DefaultRequestHeaders.Add("ContentType", "application/json");
        
    //This is the key section you were missing    
    var plainTextBytes = System.Text.Encoding.UTF8.GetBytes("testing:123456");
    string val = System.Convert.ToBase64String(plainTextBytes);
    httpClient.DefaultRequestHeaders.Add("Authorization", "Basic " + val);
        
    HttpResponseMessage response = httpClient.GetAsync(url).Result;
    string content = string.Empty;
        
    using (StreamReader stream = new StreamReader(response.Content.ReadAsStreamAsync().Result, System.Text.Encoding.GetEncoding(_encoding)))
    {
         content = stream.ReadToEnd();
    }
like image 179
Edney Holder Avatar answered Sep 19 '22 07:09

Edney Holder