6.61Implementing Automatic Authorization Token Refresh

Created on Aug 17, 2026~3 min read

When integrating with third-party API interfaces, it is usually necessary to carry an authorization Token in the request header. Because a Token is time-sensitive, developers need to refresh the Token periodically. The following example shows how to implement automatic Token refresh logic via DelegatingHandler. When the response returns a 401 status code, the system automatically re-fetches the authorization Token and updates the request header.

cs
public class AuthorizationDelegatingHandler : DelegatingHandler{    protected override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken)    {        // See the SendAsync code        return base.Send(request, cancellationToken);    }    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,        CancellationToken cancellationToken)    {        // Clone the original request (to solve the problem that StreamContent can only be read once)        var clonedRequest = await request.CloneAsync(cancellationToken);        // Send the request for the first time        var response = await base.SendAsync(clonedRequest, cancellationToken);        // Detect the 401 status code        if (response.StatusCode != HttpStatusCode.Unauthorized)        {            return response;        }        // Refresh the Token        var newToken = await GetNewTokenAsync(); // Implement the logic for getting a new Token        // Clone the request again and add the new Token        clonedRequest = await clonedRequest.CloneAsync(cancellationToken);        clonedRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", newToken);        // Retry the request        response = await base.SendAsync(clonedRequest, cancellationToken);        return response;    }    private async Task<string> GetNewTokenAsync()    {        // Implement the logic for getting a new Token here        // For example: call the authentication service to get a new Token        return "newToken";    }}

Next, register AuthorizationDelegatingHandler in the Program.cs or Startup.cs file:

csharp
// Register AuthorizationDelegatingHandler as a serviceservices.TryAddSingleton<AuthorizationDelegatingHandler>();// Enable AuthorizationDelegatingHandler for the default HttpClient clientservices.AddHttpClient()    .AddHttpMessageHandler<AuthorizationDelegatingHandler>();// To enable it for a specific named HttpClient client, configure as follows// services.AddHttpClient("weixin")//     .AddHttpMessageHandler<AuthorizationDelegatingHandler>();

With the above code, we have implemented an automatic Token refresh mechanism. When the Token expires, the system automatically obtains a new Token and retries the request, thereby ensuring continuous and effective communication with third-party APIs.