I am using IHttpClientFactory for sending requests and receiving HTTP responses from two external APIs using Net Core 2.2.
I am looking for a good strategy to get a new access token using a refresh token that has been stored in the appsettings.json. The new access token needs to be requested when the current request returns 403 or 401 errors, When the new access and refresh token have been obtained, the appsettings.json needs to be updated with the new values in order to be used in subsequent requests.
I am using two clients to send requests to two different APIs but only one of them use token authentication mechanism.
I have implemented something simple that works but i am looking for a more elegant solution that can update the header dynamically when the current token has expired :
I have registered the IHttpClientFactory in the Startup.ConfigureServices method as follows:
services.AddHttpClient();
Once registered i am using it in two different methods to call two different APIs, the first method is:
public async Task<AirCallRequest> GetInformationAsync(AirCallModel model)
{
try
{
CandidateResults modelCandidateResult = null;
var request = new HttpRequestMessage(HttpMethod.Get,
"https://*******/v2/*****");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _appSettings.Value.Token);
var clientJAAPI = _httpClientFactory.CreateClient();
var responseclientJAAPI = await clientJAAPI.SendAsync(request);
if (responseclientJAAPI.IsSuccessStatusCode)
{
modelCandidateResult = await responseclientJAAPI.Content
.ReadAsAsync<CandidateResults>();
....
}
if ((responseclientJAAPI .StatusCode.ToString() == "Unauthorized")
{
await RefreshAccessToken();
//Calls recursively this method again
return await GetInformationAsync(model);
}
return null;
}
catch (Exception e)
{
return null;
}
}
The refresh Token method looks like that:
private async Task RefreshAccessToken()
{
var valuesRequest = new List<KeyValuePair<string, string>>();
valuesRequest.Add(new KeyValuePair<string, string>("client_id", "*****"));
valuesRequest.Add(new KeyValuePair<string, string>("client_secret","****"));
valuesRequest.Add(new KeyValuePair<string, string>("grant_type", "refresh_token"));
valuesRequest.Add(new KeyValuePair<string, string>("refresh_token", "*****"));
RefreshTokenResponse refreshTokenResponse = null;
var request = new HttpRequestMessage(HttpMethod.Post,
"https://*****/connect/token");
request.Content = new FormUrlEncodedContent(valuesRequest);
var clientJAAPI = _httpClientFactory.CreateClient();
var responseclientJAAPI = await clientJAAPI.SendAsync(request);
if (responseclientJAAPI.IsSuccessStatusCode)
{
refreshTokenResponse = await responseclientJAAPI.Content.ReadAsAsync<RefreshTokenResponse>();
//this updates the POCO object representing the configuration but not the appsettings.json :
_appSettings.Value.Token = refreshTokenResponse.access_token;
}
}
Notice that I am updating the POCO object representing the configuration but not the appsettings.json, so the new values are stored in memory. I want to update the appsettings.json for subsequent requests.
If the solution proposed require to define the main settings for the Httpclient in the Startup.ConfigureService, it needs to allow to create different instances of the HttpClien, because one of the HttpClient instances (use in another method to call a second API) doesn't require a token to send the requests.