Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient logging sensitive data

Is it possible to disable logging headers of requests/responses performed using HttpClient at every log level?

Registering custom HttpClient into DI like this:

services.AddHttpClient<CustomHttpClient>(config =>
{
    config.BaseAddress = new Uri(CustomBaseAddress);
    config.DefaultRequestHeaders.Authorization = new(AuthorizationKey, AuthorizationValue);
});

After request is performed logs are looking like this:

info: System.Net.Http.HttpClient.CustomHttpClient.LogicalHandler
      Start processing HTTP request GET {CustomBaseAddress}
trce: System.Net.Http.HttpClient.CustomHttpClient.LogicalHandler
      Request Headers:
      Authorization: {AuthorizationKey} {AuthorizationValue}

I know I can set min log level in app configuration for System.Net.Http.HttpClient.CustomHttpClient to none (or something higher that trace). But I want to avoid doing that.

So is there a way how to configure HttpClient to not logging headers?

like image 983
Petr Nečas Avatar asked Oct 18 '25 15:10

Petr Nečas


1 Answers

I finally ended up with pretty easy solution. And its by using extension method HttpClientBuilderExtensions.RedactLoggedHeaders

Example:

services.AddHttpClient<CustomHttpClient>(config =>
{
    config.BaseAddress = new Uri(CustomBaseAddress);
    config.DefaultRequestHeaders.Authorization = new(AuthorizationKey, AuthorizationValue);
})
.RedactLoggedHeaders(new string[] { "Authorization" });

This method hides headers values before logging.

from this:

trce: System.Net.Http.HttpClient.CustomHttpClient.LogicalHandler
      Request Headers:
      Authorization: {AuthorizationKey} {AuthorizationValue}

to this:

trce: System.Net.Http.HttpClient.CustomHttpClient.LogicalHandler
      Request Headers:
      Authorization: *
like image 131
Petr Nečas Avatar answered Oct 21 '25 03:10

Petr Nečas