(616) 371-1037

[email protected]

Calling APIs with OAuth2 Access Tokens – The Easy Way!

June 3, 2021 - John Waters

No Comments

Scenario: Your API needs to call another REST API – or your Console App or Web Job needs to call some other REST API. You can acquire an access token to that API from an OAuth2 Security Token Service such as Duende Identity Server, Okta, Auth0 or Azure Active Directory. This blog shows you how to acquire those access tokens on demand when you need them, automatically refresh them if they expire, and use them calling your API…all with pretty much NO CODE! Just code that does configuration…

There’s a helpful picture in this article – we are doing the Web API to Web API scenario, or the Server to Web API.

In the examples below I will assume you are using dotnet core 5, in particular ASP.NET Core 5 – but it could be a dotnet core Console App or Web Job – and there are similar libraries and approaches for full .NET Framework apps too. I also assume you are familiar with the concepts of OAuth2.

All the magic happens in one place – when setting up your Dependency Injection in your application’s ConfigureServices method, typically found in your Startup.cs or maybe in your Program.cs CreateDefaultBuilder. Let’s break down the steps.

First of all, we are going to be calling a REST API using HttpClient. We are going to wrap this in a service, a helper class, here called FileApiCaller. In order to inject this service where we need it, we will create an interface for it. Here is a simplified version:

    public interface IFileApiCaller
    {
        Task<List<FileMetaDataDto>> SearchAsync(FileSearchDTO search);
    }

And here is a snippet from the implementation of the service:

    public class FileApiCaller : IFileApiCaller
    {
        private readonly HttpClient _httpClient;

        public FileApiCaller(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public async Task<List<FileMetaDataDto>> SearchAsync(FileSearchDTO search)
        {
            var response = await _httpClient.PostAsJsonAsync("api/files/search", search);
            return await response.Content.ReadFromJsonAsync<IEnumerable<FileDTO>>();
        }
    }

I register this service in my ConfigureServices, telling the Dependency Injection system that whenever I ask for an IFileApiCaller, please create a FileApiCaller object for me:

services.AddScoped<IFileApiCaller, FileApiCaller>();

Now let’s study the code excerpt for the FileApiCaller in more detail. You will note that the service is passed an instance of HttpClient in its constructor, stores it in a field, and then uses it to make the call the API and return a response… but where is the REST API base URL? And where is the logic to get and cache an OAuth2 access token, check if it has expired and get a new one using a refresh token, and pass it in the Authorization header?

Let’s go back to ConfigureServices, where we find these lines of code:

    var idso = Configuration.GetSection("IdentityServer").Get<IdServerOptions>();

    services.AddAccessTokenManagement(options =>
    {
        options.Client.Clients.Add("identityserver", new ClientCredentialsTokenRequest
        {
            Address = $"{idso.IdServerUrl}/connect/token",
            ClientId = idso.ClientId,
            ClientSecret = idso.ClientSecret,
            Scope = idso.Scopes
        });
    });

    var fao = Configuration.GetSection("FileApi").Get<FileApiOptions>();

    services.AddHttpClient<IFileApiCaller, FileApiCaller>(client =>
        {
            client.BaseAddress = new Uri(fao.ApiUrl);
            client.Timeout = TimeSpan.FromMinutes(5);
        })
        .AddClientAccessTokenHandler();

Let’s break down the code snippet above!

First up, we get the OAuth endpoint configuration from our Configuration:

var idso = Configuration.GetSection("IdentityServer").Get<IdServerOptions>();

This options object includes the URL to IdentityServer, as well as our ClientID and Client Secret, and the Scopes we wish to ask for. These could come from appsettings.json, user secrets, Azure Configuration, Azure Key Vault or maybe all of the above. You can read more about Configuration in ASP.NET Core here. This is the options class used to hold these IdentityServer settings (remember this could be any OAuth2 STS).

    public class IdServerOptions
    {
        public string IdServerUrl { get; set; }
        public string ClientId { get; set; }
        public string ClientSecret { get; set; }
        public string Scopes { get; set; }
    }

Next, is services.AddAccessTokenManagement. This comes from the IdentityModel.AspNetCore Nuget Package:

<PackageReference Include="IdentityModel.AspNetCore" Version="3.0.0" />

This code adds Access Token Management to the DI container, and configures it with the values read from our configuration. You can of course call multiple different REST APIs with different access tokens, so we give this particular token configuration a name “identityserver”. 

    services.AddAccessTokenManagement(options =>
    {
        options.Client.Clients.Add("identityserver", new ClientCredentialsTokenRequest
        {
            Address = $"{idso.IdServerUrl}/connect/token",
            ClientId = idso.ClientId,
            ClientSecret = idso.ClientSecret,
            Scope = idso.Scopes
        });
    });

Next, I am going to read the configuration for the API I want to call, including the base URL to use:

    var fao = Configuration.GetSection("FileApi").Get<FileApiOptions>();

Here is that Options class:

    public class FileApiOptions
    {
        public string ApiUrl { get; set; }
        ...
    }

And finally, I am going to add HttpClient to the DI container, and say that when an instance of FileApiCaller is created where an IFileApiCaller is called for, I want the injected HttpClient to be configured with the BaseAddress specified:

    services.AddHttpClient<IFileApiCaller, FileApiCaller>(client =>
        {
            client.BaseAddress = new Uri(fao.ApiUrl);
            client.Timeout = TimeSpan.FromMinutes(5);
        })
        .AddClientAccessTokenHandler();

Additionally, I am saying I want the AccessTokenHandler to automatically get tokens, renew them and provide them in the Authorization: Bearer {accessToken} HTTP Header when I make calls with this HttpClient.

If you haven’t read about AddHttpClient, head over to this documentation. This is a great pattern. It actually uses an HttpClientFactory to allocate HttpClients when needed, which share a pool of HttpMessageHandlers to reduce resource consumption. You can also configure things like Polly (for repeating/retrying failed calls), and message handlers in your Http call pipeline. You see this in action in the chained call to AddClientAccessTokenHandler – this is where a MessageHandler is added to your HttpClient that takes care of acquiring, refreshing and using your OAuth API access token (in this case from IdentityServer).

To summarize so far: the FileApiCaller service just accepts an HttpClient instance and uses it to call the REST API. It arrives preconfigured with the correct Base URL, and with the ability to acquire and use access tokens. All of this is thanks to a few lines of setup code in ConfigureServices.

The last piece of the puzzle is using this FileApiCaller service in say your own API controller (or it could be from your console app).

    public class ClaimController : ApiController
    {
        private readonly IFileApiCaller _fileApiCaller;

        public MyClaimController( IFileApiCaller fileApiCaller )
        {
            _fileApiCaller = fileApiCaller;
        }

        [HttpGet]
        [Route("{myClaimId:int}/files")]
        public async Task<ActionResult<List<FileMetaDataDto>>> GetFilesForMyClaimAsync(
            int myClaimId, 
            [FromQuery] int width = 1280, 
            [FromQuery] int height = 800)
        {
                return await _fileApiCaller.SearchAsync(new FileSearchDTO
                {
                    AgreementId = claim.ConsumerPlan,
                    ClaimId = claim.ClaimNumber,
                    ThumbnailWidth = width,
                    ThumbnailHeight = height,
                    ExcludeDocumentTypes = new []
                    {
                        (int)FBDocumentType.ManufacturerInvoiceReceipt, 
                        (int)FBDocumentType.DeliveryReceipt
                    }
                });
        }

The FileApiCaller is injected through the IFileApiCaller in the constructor, stored in a field, and then used when “GetFilesForMyClaimAsync” is called. As you can see, nowhere is there any code related to acquiring, refreshing or using access tokens! It’s all taken care of for you if you just set things up right!

Like many complex things – once you understand the correct way to use them they are actually quite simple!

Happy OAuth2 You!

John Waters

Leave a comment

Your email address will not be published. Required fields are marked *