Mike Bruno
Mike Bruno

Reputation: 589

Silently authenticate to a URL via basic auth in C#

I need to build a C# application which accepts a specific URL as input and loads the webpage (which is all text) into a string. The difficulty is that this URL requires basic authentication in order to load the page. I need to hard-code the credentials into the app; I can't have the user enter it themselves. I don't believe it is possible to pass the username & p/w in as part of the URL. Is there a way to handle this silently with C#?

Here is how, in very basic terms, I would load the page if authentication wasn't required:

static void Main(string[] args)
{
    if (args.Length == 0)
        return;

    WebClient webclient = new WebClient();
    string output = webclient.DownloadString(args[0]);
    Console.WriteLine(output);
}

Upvotes: 0

Views: 3173

Answers (1)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

Basic authentication is just a header in your request to the webserver. Add the Authorization header along with the correct values and you are good.

The following is an example of that header:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

Basic is required because you want to use the basic authentication
QWxhZGRpbjpvcGVuIHNlc2FtZQ== is the Base64 representation of username:password, in this case Aladdin:open sesame

When using the WebClient class, you don't have to write that header yourself, you can use the Credentials property before the call to DownloadString:

webclient.Credentials = new NetworkCredential(userName, password);

Upvotes: 7

Related Questions