1

I have an async method that uses HttpClient:

 private static HttpClient client = new HttpClient();   //As pointed by @maccettura
 private async Task<string> GetResult(Uri url, string user, string pass)
 {

    var PassArray = new UTF8Encoding().GetBytes(user + ":" + pass);

        client.BaseAddress = url;

        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(_passArray));

        string result;

        using (HttpResponseMessage response = await client.GetAsync(url))
        using (HttpContent content = response.Content)
        {
            result = await content.ReadAsStringAsync();
        }
        return result;
    }

That I had to change to synchronous WebClient

     private string GetResult(Uri url, string user, string pass)
    {
        using (var client = new WebClient())
        {
            client.UseDefaultCredentials = true;
            client.Credentials = new NetworkCredential(user, pass);
            using (var stream = client.OpenRead(url))
            using (var streamReader = new StreamReader(stream, Encoding.UTF8, true))
            {
                return streamReader.ReadToEnd();
            }
        }
    }

Am I compromising security by sending plain username and password? If so, is there a way to increase the security? (the url is a Https address)

Yasskier
  • 791
  • 1
  • 14
  • 36

2 Answers2

1

In both cases you send credentials in "plain text". In both cases they are converted to base-64 before sending, but that does not make it any more secure. The only difference is that in second (WebClient) case web client will first make request without credentials. Then it will get 401 Unauthorized response and after that it will make second request with the exact same Authorization Basic <base64_here> header, so it's kind of less efficient than applying that header right away. But again both cases send exactly the same Authorization header. As already said - if you make request to https endpoint, your credentials should be safe against interception by third party, no need to implement your own encryption if you are already using encrypted channel.

Evk
  • 98,527
  • 8
  • 141
  • 191
0

Yes you are compromising by sending plain text username and password. There can be network sniffers that can pick up the packages you send accross http and read them. If user name and passwords are plain then uh-oh. Sniffers usually sniff in public places like libraries and coffee shops.

sdfbhg
  • 109
  • 5