简体   繁体   中英

C# Windows Store App HTTPClient with Basic Authentication leads to 401 “Unauthorized”

I am trying to send a HTTP GET request to a service secured with BASIC authentication and https. If I use the RESTClient Firefox plugin to do so there is no problem. I am defining the basic-header and sending the GET to the url and I am getting the answer (data in json).

Now I am working on a Windows Store App in C# which is meant to consume the service. I enabled all required capabilities in the manifest and wrote the following method:

private async void HttpRequest()
        {
            string basic = "Basic ...........";

            Uri testuri = new Uri(@"https://...Servlet");

            HttpClient client = new HttpClient();

            client.DefaultRequestHeaders.Add("Authorization", basic);

            Task<HttpResponseMessage> response = client.GetAsync(testuri);
            var text = await response;
            var message = text.RequestMessage;
        }

I tried out many different possibilites like getting the response-string but everything lead to an 401 Status Code answer from the Server.

I looked at many similar problems and my understanding of the communication is the following: Client request -> Server response with 401 -> Client sends Authorization header -> Server response with 200 (OK)

What I don't understand is why I am getting the 401 "Unauthorized" Status Code although I am sending the Authorization header right at the beginning. It would be interesting if someone knows how this is handled in the RESTClient.

The BASIC header is definetly correct I was comparing it with the one in the RESTClient.

It would be great if someone could help me with this.

Thanks in advance and kind regards, Max

Was having a similar problem, i added a HttpClientHandler to HttpClient.

var httpClientHandler = new HttpClientHandler();
httpClientHandler.Credentials = new System.Net.NetworkCredential("","")
var httpClient = new HttpClient(httpClientHandler);

Credentials should be encoded, before adding to the header. I tested it in WPF app, It works...

      string _auth = string.Format("{0}:{1}", "username", "password");
      string _enc = Convert.ToBase64String(Encoding.UTF8.GetBytes(_auth));
      string _basic = string.Format("{0} {1}", "Basic", _enc);

      HttpClient client = new HttpClient();
      client.DefaultRequestHeaders.Add("Authorization",_basic);

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