0

How do I call a RESTful service and pass in basic auth. This is username and password along with authorization basic.

 using (var httpClient = new HttpClient())
            {
                //var request = new StringContent(messageBody);
                //request.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                httpClient.BaseAddress = new Uri(serviceUrl);
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var credentials = Encoding.ASCII.GetBytes("myadmin:mypassword");
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(credentials));

                //var response = await httpClient.PostAsJsonAsync(serviceUrl, customer);
                HttpResponseMessage response = await httpClient.PostAsJsonAsync("url here", customer);
            }
Funky
  • 12,890
  • 35
  • 106
  • 161
  • What do you send now? What is server response? – Sergey Berezovskiy May 02 '17 at 13:37
  • Curently just pass the object over, but I need to set the basic auth aswell for username and password, which I'm not sure how to do – Funky May 02 '17 at 13:39
  • Possible duplicate of [C# HttpWebRequest using Basic authentication](http://stackoverflow.com/questions/4334521/c-sharp-httpwebrequest-using-basic-authentication) – KSib May 02 '17 at 13:40
  • @Ksib possible....but not a duplicate! – Funky May 02 '17 at 14:00
  • Seems like a duplicate to me. Explain how its different. You want to make a post to a service with basic authentication. Seems the same. I also googled your exact title and got results for what you want to do. [this](http://stackoverflow.com/questions/18347055/calling-a-rest-api-with-username-and-password-how-to) was the other result – KSib May 02 '17 at 14:02
  • @ksib that one is a GET, mine is a POST – Funky May 02 '17 at 14:08
  • You should specify that in your post. – KSib May 02 '17 at 14:15
  • @Ksib see above in desc – Funky May 02 '17 at 14:23

1 Answers1

0

You have to concatenate the username and the password with a colon, encode the value to base64 and then add this value to the Authorization header with "Basic" scheme.

Akos Nagy
  • 4,201
  • 1
  • 20
  • 37