Using my WCF http Basic Authentication code in VS 2012

I blogged about the implementation of http basic authentication that I made in this post here, but this is a more detailed description of how to get it working in a simple WCF service in Visual Studio 2012.

First, you'll need to set up a basic out-of-the-box WCF service in Visual Studio 2012:

...and change it slightly so that it can be used from a browser, as described in this post here. You should now be able to call your service from any web browser to see it's working properly.

Personally, I just stuck to the default Microsoft code example and added a [WebGet] attribute, like this:

[WebGet(UriTemplate="getdata?num={value}")]
public string GetData(int value)
{
   return string.Format("You entered: {0}", value);
}

...which means that I can call http://localhost:8080/Service1.svc/getdata?num=1 to pass a querystring value to my method.

Now, add these files to your project (BasicAuthenticationAttribute.cs, BasicAuthenticationHttpHeaderInjector.cs and BasicAuthenticationPasswordValidator.cs). When you've done that, just add the [BasicAuthentication] attribute to your service class. That's it! Try running the project again.

You should be asked for a username and password by the browser. Now, the WCF service will only return some data when you have used these details: username='user' and password='password'. You can change the BasicAuthenticationPasswordValidator class to implement whatever means you like to check that the user is authorised.

You now have a code-only implementation of http basic authentication for WCF. If you're using IIS, you don't need to configure anything to make this work, as far as IIS is concerned you are using anonymous access. But it should also work in IIS Express or the Visual Studio Development Server.

NOTE: this code makes no attempt to encrypt the username and password you type into the browser. The details will be sent in clear text as an http header. You should at least consider using https to encrypt the data. The purpose of this code is just to show how http basic authentication works, and how it could be done in code.