Using VS 2017 .Net 4.5.2
I have the following class
public static class MyHttpClient
{
//fields
private static Lazy<Task<HttpClient>> _Client = new Lazy<Task<HttpClient>>(async () =>
{
var client = new HttpClient();
await InitClient(client).ConfigureAwait(false);
return client;
});
//properties
public static Task<HttpClient> ClientTask => _Client.Value;
//methods
private static async Task InitClient(HttpClient client)
{
//resey headers
client.DefaultRequestHeaders.Clear();
//Set base URL, NOT thread safe, which is why this method is only accessed via lazy initialization
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["baseAddress"]);//TODO: get from web.config? File? DB?
//create new request to obtain auth token
var request = new HttpRequestMessage(HttpMethod.Post, "/ouath2/token"); //TODO: get from web.config? File? DB? prob consts
//Encode secret and ID
var byteArray = new UTF8Encoding().GetBytes($"{ConfigurationManager.AppSettings["ClientId"]}:{ConfigurationManager.AppSettings["ClientSecret"]}");
//Form data
var formData = new List<KeyValuePair<string, string>>();
formData.Add(new KeyValuePair<string, string>("grant_type", "refresh_token"));
formData.Add(new KeyValuePair<string, string>("refresh_token", ConfigurationManager.AppSettings["RefreshToken"]));
//set content and headers
request.Content = new FormUrlEncodedContent(formData);
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
//make request
var result = await HttpPost(request, client).ConfigureAwait(false);
//set bearer token
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", (string)result.access_token);
//TODO: error handle
}
private static async Task<dynamic> HttpPost(HttpRequestMessage formData, HttpClient client)
{
using (var response = await client.SendAsync(formData).ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();//TODO: handle this
return await response.Content.ReadAsAsync<dynamic>().ConfigureAwait(false);
}
}
}
Still in progress but I've hit a snag.
This works fine if the token only needs to be fetched once in an applications life, however the API I'm talking to uses short lived bearer tokens (15mins).
As I'm using HttpClient as a static to be reused, I cannot change the Default request headers as they are not threadsafe. But I'm required to request a Bearer token every 15mins.
How would I achieve obtaining a new bearer token and setting the default header in this particular scenario?