Authentication

WebApiClient exposes an IAuthentication interface that allows you to write your own authentication mechanism. Windows based authentication like NTLM uses credentials to set automatically the authorization header. In other types of authentication we need to set it explicity.

WebApiClient comes with 2 types of authentication: WindowsIntegratedAuthentication and BearerTokenAuthentication. Keep in mind that your WebApi server must be configured appropriately :-)

Using Windows Authetication

To set it up we use the WebApiClientOptions object. Let's see how to configure it to use username and password:

WebApiClientOptions options = new WebApiClientOptions() {
		BaseAddress = "http://localhost/testapi",
		Controller = "restaurants",
		Authentication = new WindowsIntegratedAuthentication(userName, password)
	};

using(WebApiClient<Restaurant> client = new WebApiClient<Restaurant>(options))
{
	try
	{
		//Do stuff
	}
	catch (WebApiClientException e)
	{
		//when access is denied, StatusCode equals to Unauthorized
		Assert.AreEqual(HttpStatusCode.Unauthorized, e.StatusCode);
	}
}

If we want to use default windows credentials, we just need to create a handler:

WebApiClientOptions options = new WebApiClientOptions("http://localhost/testapi", "restaurants");

var handler = new HttpClientHandler() { UseDefaultCredentials = true };

using(WebApiClient<Restaurant> client = new WebApiClient<Restaurant>(options, handler))
{
	//Do stuff
}

If we want to specify the authentication type (supported types are NTLM, Negotiate, Kerberos, Basic), we must first create a CredentialCache object:

CredentialCache cc = new CredentialCache();
cc.Add(new Uri("http://localhost/testapi"), "NTLM", new NetworkCredential(userName, password));

WebApiClientOptions options = new WebApiClientOptions() {
		BaseAddress = "http://localhost/testapi",
		Controller = "restaurants",
		Authentication = new WindowsIntegratedAuthentication(cc)
	};

using(WebApiClient<Restaurant> client = new WebApiClient<Restaurant>(options))
{
	//Do stuff
}

Using Bearer Token Authetication

Let's see how to use it:

//this is the location where the bearer token will be generated and returned
string tokenUri = "http://localhost/testapi/token";

WebApiClientOptions options = new WebApiClientOptions() {
		BaseAddress = "http://localhost/testapi",
		Controller = "restaurants",
		Authentication = new BearerTokenAuthentication(userName, password, tokenUri);
	};

using(WebApiClient<Restaurant> client = new WebApiClient<Restaurant>(options))
{
	try
	{
		//Do stuff
	}
	catch (WebApiClientException e)
	{
		if (e.StatusCode == HttpStatusCode.Unauthorized)
		{
			//when access is denied, StatusCode equals to Unauthorized
		}
		if (e.StatusCode == HttpStatusCode.ServiceUnavailable)
		{
			//when tokenUri is invalid, StatusCode equals to ServiceUnavailable
		}
	}
}

Once the token is generated, WebApiClient stores it and uses the same token during the lifetime of the object.