In this article, we will review the different authenticator types in RestSharp, available via NuGet. First, we will briefly look through all of them and later focus on setting up a request using the HTTP basic authenticator. Then we will take a look at a common error encountered, why we get it, and how to address it.

To download the source code for this article, you can visit our GitHub repository.

Let’s start.

RestSharp Overview

RestSharp is a popular open-source library for making HTTP requests in .NET applications. It simplifies interacting with web services and APIs by providing a high-level and easy-to-use interface. It also comes in handy when building RESTful web service clients.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!
To learn more about RestSharp, check out our Using RestSharp To Consume APIs in C# article, which goes more in-depth on how to set everything up.

When using RestSharp, we have a variety of authenticators to choose from:

  • Basic HTTP – utilizes a simple username and password mechanism for authentication
  • JWT – adds a Bearer token to the Authorization header for requests and supports token refresh
  • OAuth1  – supports OAuth 1.0a protocol with a request or access tokens
  • OAuth2 -supports  OAuth 2.0 protocol by sending the access token as a bearer token in the request header
  • Custom authenticator – implements the IAuthenticator interface

In our case, we focus on implementing Basic HTTP, where we send the username and password as part of the HTTP request headers. To learn more, please see our existing HTTP Authentication Mechanisms article.

Now, let’s set everything up and see it in action!

New Project Setup

Let’s create a new console application using the .NET CLI:

dotnet new console

Also, we need to install RestSharp via NuGet:

dotnet add package RestSharp

For testing purposes, we use the https://httpbin.org API, which provides a variety of HTTP-related services and endpoints for testing and debugging HTTP requests, including using different types of authentications. Since we want to test HTTP basic authentication, we use one of the Auth controller methods, the /basic-auth/{user}/{passwd} method.

Now, when we have everything ready, let’s use RestSharp to make our request using HTTP basic authentication.

Use the Authenticator Property on the RestSharp Client

When setting up authentication in RestSharp, we can do it client-wide or per each request individually. In our case, we want client-wide, which means setting up authentication once, and each subsequent request from the same client is authenticated.

So following RestSharp’s official documentation we set it up:

private const string baseUrl = "https://httpbin.org";

public static async Task Main()
{
   var options = new RestClientOptions(baseUrl)
   {
       Authenticator = new HttpBasicAuthenticator("user", "pass")
   };

   var client = new RestClient(options);

   var request = new RestRequest("/basic-auth/user/pass");
   var response = await client.ExecuteGetAsync(request);

   Console.WriteLine(response.StatusCode);
}

Initially, we set a base URL for the client to "https://httpbin.org". Within the main method, we instantiate a new RestClientOptions one and configure its Authenticator property. This property populates requests with the necessary authentication data. We provide a username and password within its constructor, assigning “user” and “pass” respectively.

Next, we create a new instance of RestClient utilizing the previously defined options. Now we define the RestRequest object. Here, we specify the path to the desired route, "/basic-auth/user/pass". Finally, we execute the request and log the response’s status code.

What is important to note here is that we replaced the placeholder values in the route path {user}/{passwd} with values that we used when setting up the new authenticator (“user” and “pass”).

The server expects the provided username and password in the path to match the credentials supplied in the HTTP request headers for basic authentication to work correctly.

If we set up everything correctly, the StatusCode in the provided response should be 200 OK. Additionally, we can confirm authentication success by checking the response Content variable:

{
  "authenticated": true, 
  "user": "user"
}

Now that everything works, let’s look at a common error that can occur during this setup.

A Common Error When Setting Up the Authenticator

When setting up a new authenticator in RestSharp, we might encounter a common error: Property or indexer 'RestClient.Authenticator' cannot be assigned to -- it is read only. This happens if we try to set the Authenticator property directly on the client:

var client = new RestClient(options);
client.Authenticator = new HttpBasicAuthenticator("user", "pass");

Also, the same error occurs if we try to set it as part of instantiation:

var client = new RestClient() 
{ 
    Authenticator = new HttpBasicAuthenticator("user", "pass")
};

Both of these approaches are now outdated for configuring a new authenticator. These methods were applicable before the release of RestSharp v109 where the Authenticator property became obsolete.

Using the newest version of RestSharp NuGet, instead of setting the Authenticator property on the client, we need to set it on the RestClientOptions object itself. There are lots of examples using the “old way” of setting it up, so it is good to be up to date and check the official documentation. We can find more information about the new versions and migration in the RestSharp migration guide

Conclusion

In this article, we saw how to set up HTTP basic authenticator requests using RestSharp NuGet. Also, we saw what other authenticators are available when using this Nuget.

We used a convenient example for testing and demonstration purposes where the username and password are a part of both the URL and the request headers as part of the basic authentication. However, it’s crucial to avoid including sensitive information like usernames and passwords directly in the URL in a real-world scenario due to security risks

Furthermore, consider reading sensitive information, such as usernames and passwords, from a secure configuration source rather than hardcoding them directly into the code. To learn more about securing sensitive information please check out our article about Securing Sensitive Data Locally, or read the Azure Key Vault article when using Azure.

In the last part of the article, we examined a common error we might encounter due to the recent RestSharp improvements.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!