Leon V
Leon V

Reputation: 631

Retrieving auth token with async for use via HttpClientFactory

I'm trying to configure HttpClientFactory to use an Authorization header. The problem is that the auth token has to be retrieved from an auth service, which is another HTTP call that better be done with await. However, this doesn't work as expected (at least not in ASP.NET Core 2.2):

// Func<IServiceProvider, Task<string>> tokenFactory = ...
builder.ConfigureHttpClient(async (provider, httpClient) =>
{
    string token = await tokenFactory(provider);
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
});

It looks like whenever the action passed to ConfigureHttpClient is involved, it's not awaited.

Any ideas on workarounds? Should ConfigureHttpClient be improved or I'm missing some existing functionality that would allow doing that?

Upvotes: 3

Views: 1655

Answers (1)

Frederik Nygart
Frederik Nygart

Reputation: 124

Look at this answer:

How to Refresh a token using IHttpClientFactory

Creating a separate DelegatingHandler for handling HttpClient request before sending the request. Within this Handler it is possible to resolve asynchronous calls.

Upvotes: 1

Related Questions