Skip to content

Headers and Authentication

Alessandro Morvillo edited this page Aug 8, 2026 · 2 revisions

Headers and Authentication

Restling supports headers at client level and request level.

Default headers

Default headers apply to every request made by the client:

HttpClientContextBuilder builder = new();

builder.AddDefaultHeader("X-App-Version", "1.0.0")
       .AddDefaultHeader("X-Tenant-ID", tenantId)
       .AddUserAgent("MyApp/1.0");

Use RemoveDefaultHeader or ClearDefaultHeaders before building the client to remove configured values.

Request-specific headers

using AMDevIT.Restling.Core.Network;

RequestHeaders headers = new();
headers.Headers.Add("X-Correlation-ID", correlationId);
headers.Headers.Add("If-Match", entityTag);

RestRequestResult<Customer> result = await client.GetAsync<Customer>(uri,
                                                                     headers,
                                                                     cancellationToken: cancellationToken);

Bearer authentication

Set a bearer token for every request:

builder.AddAuthenticationHeader("Bearer", accessToken);

Or for one request:

AuthenticationHeader authentication = new("Bearer", accessToken);
RequestHeaders headers = new(authentication);

AddAuthenticationHeader also accepts Restling's AuthenticationHeader or a .NET AuthenticationHeaderValue.

Basic authentication

BasicAuthenticationBuilder creates a correctly encoded Basic authentication value:

using AMDevIT.Restling.Core.Network;
using AMDevIT.Restling.Core.Network.Builders.Security.Headers;

BasicAuthenticationBuilder authenticationBuilder = new();
authenticationBuilder.SetUser(userName);
authenticationBuilder.SetPassword(password);

AuthenticationHeader authentication = authenticationBuilder.Build();
RequestHeaders headers = new(authentication);

RestRequestResult<Account> result = await client.GetAsync<Account>(uri,
                                                                   headers,
                                                                   cancellationToken: cancellationToken);

The password overloads accept string, SecureString, or byte[]. Prefer a representation compatible with your application's secret-management strategy, and avoid logging credentials or complete authentication values.

Clone this wiki locally