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!

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:

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! 

Montage Portal

Montage Furniture Services provides furniture protection plans and claims processing services to a wide selection of furniture retailers and consumers.

Project Background

Montage was looking to build a new web portal for both Retailers and Consumers, which would integrate with Dynamics CRM and other legacy systems. The portal needed to be multi tenant and support branding and configuration for different Retailers. Trailhead architected the new Montage Platform, including the Portal and all of it’s back end integrations, did the UI/UX and then delivered the new system, along with enhancements to DevOps and processes.

Logistics

We’ve logged countless miles exploring the tech world. In doing so, we gained the experience that enables us to deliver your unique software and systems architecture needs. Our team of seasoned tech vets can provide you with:

Custom App and Software Development

We collaborate with you throughout the entire process because your customized tech should fit your needs, not just those of other clients.

Cloud and Mobile Applications

The modern world demands versatile technology, and this is exactly what your mobile and cloud-based apps will give you.

User Experience and Interface (UX/UI) Design

We want your end users to have optimal experiences with tech that is highly intuitive and responsive.

DevOps

This combination of Agile software development and IT operations provides you with high-quality software at reduced cost, time, and risk.

Trailhead stepped into a challenging project – building our new web architecture and redeveloping our portals at the same time the business was migrating from a legacy system to our new CRM solution. They were able to not only significantly improve our web development architecture but our development and deployment processes as well as the functionality and performance of our portals. The feedback from customers has been overwhelmingly positive. Trailhead has proven themselves to be a valuable partner.

– BOB DOERKSEN, Vice President of Technology Services
at Montage Furniture Services

Technologies Used

When you hit the trails, it is essential to bring appropriate gear. The same holds true for your digital technology needs. That’s why Trailhead builds custom solutions on trusted platforms like .NET, Angular, React, and Xamarin.

Expertise

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

  • Project Management
  • Architecture
  • Web App Development
  • Cloud Development
  • DevOps
  • Process Improvements
  • Legacy System Integration
  • UI Design
  • Manual QA
  • Back end/API/Database development

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

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

Ready to come with us? 

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 contact form. 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.