简体   繁体   中英

How to handle token expiration in httpclient?

I am in front of problem below. I am using a httpclient for make requests. Also we use bearer authorization and getting token from server each one hour. I am trying to find which is the best solution for checking if our token has been expired.

Here is an example from server Response when we generate a token

{

 "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjBEOEZCOEQ2RURFQ0Y1Qzk3RUY1MjdDMDYxNkJCMjMzM0FCNjVGOUZSUzI1NiIsInR5cCI6ImF0K2p3dCIsIng1dC",
 "expires_in": 3600, //seconds
 "token_type": "Bearer",
}
  1. First solution is to create a static datetime. Then save token expiration datetime in this static datetime. Then in each request to compare current datetime with expiration datetime, and if need to generate a new token.

Is there any way to register a method in httpclient? So in each request to run this method first?

We tried to create a static method, and place it before each httpclient request. But we don't want to copy paste this method before each request. If there is a method to register a method in httpclient

Here is an httpclient example

public class HttpClientHelper
{
    private static HttpClient httpClient;
    public static HttpClient Request()
    {
        if (httpClient == null)
            httpClient = new HttpClient();
        return httpClient;
    }
}

And here is how you are making a request

var uri = "http://myurl.com"; 
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, uri))
            {
                
                using (var httpResponseMessage = await HttpClientHelper.Request().SendAsync(httpRequestMessage,
                  new CancellationTokenSource(TimeSpan.FromSeconds(10)).Token))
                {
                    if (httpResponseMessage.IsSuccessStatusCode)
                    {
                       
                    }
                }

You should be able to store the token in local memory cache and set an expiration. When the JWT is about to expire then it should invalidate the cache entry.

IMemoryCache cache = provider.GetRequiredService<IMemoryCache>();

var token = cache.Get("access_token");
if (!string.IsNullOrWhitespace(token))
{
  return token;
}

var newToken = GetAccessToken();
cache.Set("access_token", newToken, TimeSpan.FromMinutes(55));  // assuming tokens expire in 1hr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM