Add BasicAuthentication To Your Web Service Client

Building on my last post using the wsdl.exe app to build a web service client proxy, we now need to add authentication. A common practice is to send your credentials using BasicAuthentication (over HTTPS of course).

All over the web you’ll find simple examples showing you how to set the Credentials object on your proxy and voila it works. That’s great if you have a webservice that challenges you and gives your a client a chance to respond. Unfortunately though, web services typically are stateless, one time calls. There’s no chance for “hey, how ya doin?”. Here’s my solution for adding the Authorization header to the outgoing request (the first outgoing request).

You’ll still use the Credentials object in your client.

WSProxy proxy = new WSProxy();
proxy.Credentials = new NetworkCredential(username, password);
string response = proxy.HelloWorld();

The proxy object will use the Credentials object you just set if you insert this code into the WSProxy object.

/// <summary>
/// Manually insert HTTP Authorization header for Basic Authentication.
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
protected override WebRequest GetWebRequest(Uri uri)
    string username = ((NetworkCredential)Credentials).UserName;
    string password = ((NetworkCredential)Credentials).Password;
    HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri);
    string creds = String.Format("{0}:{1}", username, password);
    byte[] bytes = Encoding.ASCII.GetBytes(cre);
    string base64 = Convert.ToBase64String(bytes);
    request.Headers.Add("Authorization", "basic " + base64);
    return request;

Leave a Reply

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

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

Facebook photo

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

Connecting to %s