Blog Home  Home Feed your aggregator (RSS 2.0)  
Mayur's Blog - RestSharp with Windows Authentication
# Tuesday, December 29, 2015

Sometimes things are straight forward but easy to miss. If you are implementing a client to consume RESTful APIs and like to leverage RestSharp library, then the configuration is pretty straight forward to utilize windows authentication.

RestSharp provides "RestRequest" class. An object of "RestRequest" can be instantiated with required values such as API address and type of method (i.e. post or get or put etc.). This object can be used to enable windows authentication as shown below.

var request = new RestRequest(resource, Method.POST);
request.UseDefaultCredentials = true;

Here "UseDefaultCredentials" is set to "true" to enable windows authentication.

This is great; easy and simple. However, this would be repeating the configuration to enable windows authentication each time a new request is created. To fix this problem I would like propose an alternative. RestSharp also provides another class "RestClient". This class is actually an equivalent to "WebClient" in .NET. It exposes a few useful properties such as a base URL for the API and Authenticator. Authenticator is "IAuthenticator" type. Authenticator can be used to configure the authentication mechanism for the client. So we can implement our own Authenticator as shown below to specify windows authentication.

internal class WinAuthenticator : IAuthenticator
        public void Authenticate(IRestClient client, IRestRequest request)
            request.UseDefaultCredentials = true;

Once this is done we can make a request to an API with custom authenticator as shown below.

var client = new RestClient("BaseApiConnection");
client.Authenticator = new WinAuthenticator();
With the help of this client we can create a request as shown below
var request = new RestRequest(resource, Method.POST);
            IRestResponse response = null;
            response = client.Execute(request);
This way a single client can be shared across all the requests.
Tuesday, December 29, 2015 7:16:30 PM UTC  #       | 
Copyright © 2022 Mayur Bharodia. All rights reserved.
DasBlog 'Portal' theme by Johnny Hughes.
Pick a theme: