I just found out about the Refit library on GitHub (link: https://github.com/reactiveui/refit) . Besides my first steps in this huge world, I tried to understand why the use of this library comes handy instead of the use of the usual HttpClient when we need to make http calls towards, for example, an API service. By reading around I understood the reason that creating the httpClient by ourselves, setting the headers and other configurations, is too old style and low-level. That's where Refit takes place. I then tried to make one step forward and read about the authentication part. I noticed, according to the github page of the library, that in order to make authentication work, we need to deal again with the HttpClient that we finally managed to get rid off. The example shown on the official page is:
class AuthenticatedHttpClientHandler : HttpClientHandler
{
private readonly Func<Task<string>> getToken;
public AuthenticatedHttpClientHandler(Func<Task<string>> getToken)
{
if (getToken == null) throw new ArgumentNullException("getToken");
this.getToken = getToken;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// See if the request has an authorize header
var auth = request.Headers.Authorization;
if (auth != null)
{
var token = await getToken().ConfigureAwait(false);
request.Headers.Authorization = new AuthenticationHeaderValue(auth.Scheme, token);
}
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}
class LoginViewModel
{
AuthenticationContext context = new AuthenticationContext(...);
private async Task<string> GetToken()
{
// The AcquireTokenAsync call will prompt with a UI if necessary
// Or otherwise silently use a refresh token to return
// a valid access token
var token = await context.AcquireTokenAsync("http://my.service.uri/app", "clientId", new Uri("callback://complete"));
return token;
}
public async void LoginAndCallApi()
{
var api = RestService.For<IMyRestService>(new HttpClient(new AuthenticatedHttpClientHandler(GetToken)) { BaseAddress = new Uri("https://the.end.point/") });
var location = await api.GetLocationOfRebelBase();
}
}
I am wondering what concept am I missing here. The purpose of the library is to use more high level code, setting interfaces that are enough to call an API service. This purpose is achieved before the authentication part because all the Http settings and so on are made on purpose under the hood. But as soon as we step in this field we find again HttpHandlers, HttpRequestMessages and HttpClients losing what's the purpose of the library itself. Can someone explain me please what am I missing in the bigger picture? thanks in advance