Calling APIs with OAuth2 Access Tokens – The Easy Way!

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!

Picture of John Waters

John Waters

As a highly respected and recommended technology leader, entrepreneur, and software architect extraordinaire, John Waters provides guidance for Trailhead teams and projects. His remarkable project requirements gathering and project estimation skills allow him to oversee teams that deliver client projects on time and on budget. John’s background includes over two decades of systems architecting, implementations for a range of high-performance business solutions, and speaking at conferences worldwide.

Free Consultation

Sign up for a FREE consultation with one of Trailhead's experts.

"*" indicates required fields

This field is for validation purposes and should be left unchanged.

Related Blog Posts

We hope you’ve found this to be helpful and are walking away with some new, useful insights. If you want to learn more, here are a couple of related articles that others also usually find to be interesting:

API Security Testing: 7 Critical Checks

APIs serve as the backbone of modern applications, but without proper security testing, they can expose vulnerabilities that hackers exploit. This article covers the essential security checks for APIs, providing real-world examples, expecte

Read More

SignalR Scaling with Azure SignalR Service

SignalR is the best way to enable real-time communication in modern .NET web applications. So let's say you have built your first app with SignalR, deployed it to Azure, and everything is working great. After seeing a huge influx of new use

Read More

Our Gear Is Packed and We're Excited to Explore With You

Ready to come with us? 

Together, we can map your company’s software journey and start down the right trails. If you’re set to take the first step, simply fill out our contact form. We’ll be in touch quickly – and you’ll have a partner who is ready to help your company take the next step on its software journey. 

We can’t wait to hear from you! 

Main Contact

This field is for validation purposes and should be left unchanged.

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the form below. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Thank you for reaching out.

You’ll be getting an email from our team shortly. If you need immediate assistance, please call (616) 371-1037.