Published: January 30 2023

C# + RestSharp - Add Bearer Token Authorization Header to HTTP Request in .NET

Tutorial built with .NET 7.0 and RestSharp 108.0.3

Below is a quick example of how to add a Bearer Token Authorization Header to an HTTP request in .NET using the RestSharp HTTP client which is available on NuGet.


RestSharp Bearer Token

This sends an HTTP GET request to the Test JSON API with a couple of headers, the HTTP Authorization header and a custom header My-Custom-Header. The Test JSON API is a fake online REST API that includes a product details route (/products/{id}), the returned product includes an id and name.

Add Authorization Header

The auth header with bearer token is added to the request by calling request.AddHeader("Authorization", "Bearer my-token");.

To update an existing header call the AddOrUpdateHeader() method, e.g. request.AddOrUpdateHeader("Authorization", "Bearer my-token");.

RestSharp Authenticators

Alternatively, the same bearer token auth header can be added to the request by attaching a RestSharp JwtAuthenticator to the client, e.g. client.Authenticator = new JwtAuthenticator("my-token");. For more info see https://restsharp.dev/authenticators.html.

Deserialize JSON response

The response is deserialized to <JsonNode> so it can handle any dynamic properties returned in the response.

using RestSharp;
using System;
using System.Text.Json;
using System.Text.Json.Nodes;
                    
public class Program
{
    public static void Main()
    {
        // send GET request with RestSharp
        var client = new RestClient("https://testapi.jasonwatmore.com");
        var request = new RestRequest("products/1");
        request.AddHeader("Authorization", "Bearer my-token");
        request.AddHeader("My-Custom-Header", "foobar");
        var response = client.ExecuteGet(request);
        
        // deserialize json string response to JsonNode object
        var data = JsonSerializer.Deserialize<JsonNode>(response.Content!)!;
        
        // output result
        Console.WriteLine($"""
        ----------------
        json properties
        ----------------
        id: {data["id"]}
        name: {data["name"]}

        ----------------
        raw json data
        ----------------
        {data}
        """);
    }
}

Example C# app on .NET Fiddle at https://dotnetfiddle.net/n0yeCK


More RestSharp Examples

For more RestSharp HTTP examples see C# + RestSharp - HTTP GET Request Examples in .NET.

 


Need Some .NET Help?

Search fiverr for freelance .NET developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by