When you send a request using HttpClient, that request passes through a series of message handlers chained together forming a pipeline.
Starts with the reception of the request by the first handler, that does some specific operations and pass to the next handler in line, and so on.
At some point the request is sent, and a response is received and goes back down the pipeline.
DelegatingHandler is just the reverse of Middleware for all the outbound requests.
The problem we want to resolve is to include Authentication on all our requests , we need to request an access token and include it on every request.
We expose 2 methods
GetTokenAsync: to generate the token base on some values stored on our appsettings.json that are passed through dependency injection on the Options pattern.
IOptions<OAuthOptions> oAuthOptions
RefreshTokenAsync: to refresh the token , based on the refresh token that we receive on the GetTokenAsync.
Next we want to add this token on every request
The AuthenticationHandler class uses Polly to create an AsyncRetryPolicy, this retry policy wraps the HTTP request and retries it (3 times) when the Status code is Unauthorized or Forbidden. On each retry calls the refresh token to the AuthenticationTokenProvider gets a new token.
This allows some resilency in case of some failure on the request.
To put everything in place we need to register our AuthenticationHandler
and httpclient with our handler
We may want to include other cross-cutting concerns as logging, for that just create a handler for logging