unauthorized error when using HttpClient

12,768

For Basic Authentication, you need to send the credentials in an authorization header called "Basic" with base64-encoded "username:password" as the value. This should get the job done:

var headerVal = Convert.ToBase64String(Encoding.UTF8.GetBytes("admin@client:admin"));
var header = new AuthenticationHeaderValue("Basic", headerVal);
client.DefaultRequestHeaders.Authorization = header;
Share:
12,768
ignorantguy
Author by

ignorantguy

I am a Computer Science graduate student at Arizona State University.

Updated on June 04, 2022

Comments

  • ignorantguy
    ignorantguy almost 2 years
    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    
    namespace ConsoleProgram
    {
        public class Class1
        {
            private const string URL = "https://sun.domain.com/v1/service/token";
            static void Main(string[] args)
            {
                var handler = new HttpClientHandler();
                handler.Credentials = new System.Net.NetworkCredential("admin@client", "admin");
                HttpClient client = new HttpClient(handler);
                //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", "admin", "admin"))));
                //  client.BaseAddress = new Uri(URL);
                // Add an Accept header for JSON format.
                client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
                // List data response.
                HttpResponseMessage response = client.GetAsync(URL).Result;  // Blocking call!
                String res = response.ToString();
                Console.WriteLine(res);
            }
        }
    }
    

    I am getting unauthorized error even though I am passing the correct credentials. Any ideas?

    I tried almost all the answers posted on StackOverflow.