RestSharp and http basic authentication

Hackered
Thursday, April 9, 2015
by Sean McAlinden

For many years I thought http basic authentication was just a simple way to trick people into navigating to other sites such as http://google.com@hackered.co.uk - obviously this isn't going to google.com :)

Well I was completely wrong, it is still used legitimately and I had to use it to consume a service not so long ago.

I am currently a big fan of RestSharp so it was an easy choice for me to use it to make the http REST requests, I just needed to add a little http basic authentication into the mix.

At first I tried to just send the username and password as part of the url eg. http://myuser:mypass@theservice.com, this however did not work as RestSharp performed url encoding on the : and @.

Turns out Restsharp has this covered nicely:

var restClient = new RestClient(baseUrl)
{
    Authenticator = new HttpBasicAuthenticator(userName, password)
};

As you can see, when you create your RestClient, instantiate a new HttpBasicAuthenticator with your username and password and assign it to the RestClient Authenticator property.

Whilst I have not been left with an overwhelming feeling that http basic authentication is in any way an advisable way to authenticate with services, at least RestSharp has made it relatively pain free to deal with when you have no choice.