Sitemap

Effortlessly Renew API Tokens in ASP.NET 6.0

2 min readApr 19, 2022

--

Situation: your ASP.NET project needs to interact with an external API, and that API requires each request to have an access token, but that access token expires after a set amount of time. How do you ensure that you always have an access token ready without requesting a new one each time you instantiate your client?

Press enter or click to view image in full size
Bayfront avenue, future world @ artscience museum, singapore
Photo by Robynne Hu on Unsplash

ASP.NET 6.0 introduced PeriodicTimer for when you need a timer for doing all those asynchronous operations. Utilizing this timer with the existing BackgroundService and some handy-dandy dependency injection gives us the tools we need to make asynchronous calls to external APIs in the background of our ASP.NET application simple.

Client Interface and Implementation

Let’s start with a basic client interface and implementation. Note that on the implementation below, we have a static property for the access token. That’s going to come in handy for when we need to update the access token.

Background Service and Timer

Next, we’ll create a class for our background service. We inject the HttpClient and configure it, as well as the form content we’ll need to make our request. Modify these to meet your specific needs. We’ll also expose a property to set the token duration in seconds, so we can appropriately fire off the renewal before the existing token expires.

Wire Up Dependency Injection

All we need to do now is wire this up in our start up class, and let ASP.NET do the rest of the heavy lifting for us!

Can It BE Any More Simple?

This solution is easy to modify to suit your needs. You can inject any other objects, including configurations using the IOptions<> pattern, as long as you add the configuration before registering the hosted service (line 11), otherwise it will not be resolved.

Get Scott Offen’s stories in your inbox

Join Medium for free to get updates from this writer.

The example above also makes use the FluentHttpClient library — of which I am both author and maintainer, so this is a shameless plug — which adds extensions to make it easier and more readable to make calls using the built-in HttpClient. Check it out and start using it today!

--

--

Scott Offen
Scott Offen

Written by Scott Offen

Engineering Manager at Tech9, leading teams that build scalable software and turn complex needs into solutions with real, lasting business impact.