If I need to make an HttpRequest to a site that requires login credentials, I can use code similar to the following, but as you can see the username and password are just base64 encoded, which means that if someone were to intercept the http request all they have to do is search for the value associated with the “Authorization” header and they have my login information.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://...");
request.Headers.Add("Authorization",
string.Format("Basic {0}", Convert.ToBase64String(Encoding.Default.GetBytes(
string.Format("{0}:{1}", username, password)))));
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream s = response.GetResponseStream())
{
using (StreamReader r = new StreamReader(s))
{
DoSomething(r.ReadToEnd());
}
}
}
Is the following code a better alternative or does it also make http requests with the “Basic ” Authorization header?
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential(username, password);
DoSomething(wc.DownloadString("https://..."));
If neither code results in http requests that “hide” the login credentials and if there is actually a way to “hide” them, what’s the proper way to do it?
If you’re making a webrequest to a server using HTTPS your entire message including headers are encrypted. So there is essentially no need for you to worry about encrypting your data. If you were to open Wireshark and try and sniff the packets, you’d see they are unreadable.
The .NET Framework will take care of the SSL encryption required under the hood based on the URL you’re sending requests to.
More information can be found on MSDN: http://msdn.microsoft.com/en-us/library/ds8bxk2a.aspx