Add digest authentiacation to a client built by IHttpFactory

610 Views Asked by At

I am building an API which exposes a POST endpoint which accepts environment details containing keys which map to uris) in the request. Then this API depending on the request data passed, will send POST requests to other APIs.

Untill now, the base uri of the client was static, now the uri is dynamic and is passed from the incoming request.

The HttpClient is built in a Service class when injected through the constructor.

How can I add CredentialsCache on client that has already been built by the constructor and moce the logic from startup to on demand request?

Currently registered on Startup using an extension method

public static IServiceCollection AddUnderTest(this IServiceCollection services, ClientA settings)
    {
        var client = services
            .AddHttpClient(
            nameof(ClientA),
            c => { c.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); });

        client.ConfigurePrimaryHttpMessageHandler(
            handler => new HttpClientHandler
            {
                Credentials = new CredentialCache { {
                    new Uri(""),
                    "Digest",
                    new NetworkCredential(settings.Username, settings.Password) } }
            });
        return services;
    }

in service class

public class MyService
{

    public MyService(IHttpClientFactory htpClientFactory)
    {
        var myClient = htpClientFactory.CreateClient("ClientA");
        //add digest auth and credentials here, and not on startup
    }
}

How can I add the same configuration as in the extension methon on startup?

1

There are 1 best solutions below

0
karmelcorn On

Based on CarnaViire's reply here, Seems like if we want to dynamically set the credential digest authentication with IHttpClientFactory, we would have to manually set the request header for each call. Here is an example of setting the digest authentication header

https://callumhoughton18.github.io/Personal-Site/blog/digest-auth-in-dotnet/