1

I’m creating a class library (.NET Standard 2) where I need to pass a HttpClient to the constructor (Dependency Injection).

The class library is calling a third-party API using OAuth2 (It requests their API – with ClientID and ClientSecret – and get a token back which I’m going to use for subsequent calls).

I have some problems figuring out how to do the OAuth2 “stuff” with dependency injection.

The project I’m using the class library in – sets up the dependency in the StartUp class like: Services.AddHttpClient()

Can I somehow attach the OAuth2 “stuff” to the HttpClient?

PSXYU
  • 101
  • 2
  • 8
  • What is the "OAuth2 stuff"? If it is an HTTP header, you could set default HTTP headers to an HttpClient. – weichch Apr 01 '20 at 10:10

2 Answers2

2

What you could be doing is using a DelegatingHandler:

interface IOAuth2Stuff
{
    string Token { get; set; }
}

class OAuth2StuffRequestHandler : DelegatingHandler, IOAuth2Stuff
{
    public string Token { get; set; }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // Add OAuth2 stuff to request
        var token = Token;

        return await base.SendAsync(request, cancellationToken);
    }
}

Configure your services:

services.AddSingleton<OAuth2StuffRequestHandler>();
services.AddSingleton<IOAuth2Stuff>(provider => 
    provider.GetRequiredService<OAuth2StuffRequestHandler>());
services.AddHttpClient("ServiceHttpClient")
    .AddHttpMessageHandler<OAuth2StuffRequestHandler>();

And in your service class:

class Service
{
    public Service(IHttpClientFactory clientFactory, IOAuth2Stuff oauth2)
    {
        var client = clientFactory.CreateClient("ServiceHttpClient");
        // Do oauth2

        // Set oauth2 token to request handler.
        oauth2.Token = "blah blah";
    }
}

Note that the lifetime of the middleware isn't perfect in the example.

weichch
  • 9,306
  • 1
  • 13
  • 25
0

One way you can achieve this is with a DelegatingHandler that you can add to the HTTP Client

This answer - https://stackoverflow.com/a/56204930/1538039 - describes adding the message handler to the HttpClient instance retrieved from a HttpClientFactory.

Within the AuthenticationDelegatingHandler class, it makes a call to GetToken -> which is something you'd need to provide that takes care of token retrieval/caching/renewal, use one of the the prebuilt nuget packages that can do this for you. (i.e. https://www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory/ or equivalent)

Dylan Morley
  • 1,656
  • 12
  • 21