Basic Authentication on the Mono framework

Use the NetworkCredential constructor with username and password as strings. The SecureString constructor resulted in a request without the password in the Authorization header.

using System.Net;

var url = "http://url_to_file_to_download";
var user = "your_username";
var password = "the_password_as_a_string";
var request = WebRequest.Create(url) as HttpWebRequest;
var cred = new NetworkCredential(user, password);
var credCache = new CredentialCache();
credCache.Add(request.RequestUri, "Basic", cred);
request.Credentials = credCache;
using (var response = request.GetResponse() as HttpWebResponse) {
    using (var output = response.GetResponseStream()) {
        // handle the response stream
    }
    response.Close();
}

About erictummers

My work as a recruited developer changes almost every month. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s