Basic Authentication for a C# Web Service without configuring IIS

I have an ASP.NET C# web service (*.asmx) that I want to secure using Basic Authentication. This would also apply to a regular ASP.NET web page (*.aspx).

I could have told IIS that if someone is hitting the specific web service file (*.asmx), they need to provide Basic Authentication. But I did not want to do that because I wanted the credentials (username and password) to be stored in my application’s web.config .

So I added the following code in the web service’s constructor:

string configUsername = ConfigurationManager.AppSettings["username"];
string configPassword = ConfigurationManager.AppSettings["password"];
if (!string.IsNullOrEmpty(configUsername))
{
    //---- Check Basic Authentication credentials
    string requestUsername;
    string requestPassword;
    try
    {
        // The header is in the following format 
        // "Basic 64BitEncodedUsernameAndPasswordString"
        string userAndPassEncoded = 
            this.Context.Request.Headers["Authorization"].Substring(6);
        // userAndPasswordDecoded is in the following 
        // format "theusername:thepassword"
        string userAndPassDecoded = new System.Text.ASCIIEncoding().GetString(
            Convert.FromBase64String(
                this.Context.Request.Headers["Authorization"].Substring(6)));
        string[] userAndPasswordArray = userAndPassDecoded.Split(':');
        requestUsername = userAndPasswordArray[0];
        requestPassword = userAndPasswordArray[1];
    }
    catch (Exception ex)
    {
        throw new ApplicationException(
            "Unable to get the Basic Authentication credentials from the request"
            , ex);
    }

    if (configUsername != requestUsername || configPassword != requestPassword)
        throw new ApplicationException(
            "You are not authorized to access this web service");
}

Even though the code is not long or complex, I wonder if .NET has a class to deal with Basic Authentication (let me know if you know a better way) so I don’t need to access the headers, substring, and decode. I looked around and did not find anything so I’m leaving it as is.

Important note: Remember that Basic Authentication transmits the credentials in clear text. So you probably want to use Basic Authentication over SSL (https).

Advertisements

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