Skip to content

Commit

Permalink
Added documentation for AuthenticatedParameterizedHttpClientHandler w…
Browse files Browse the repository at this point in the history
…here signature generation is dependent on contents of the HTTP request
  • Loading branch information
Benjamin Howarth committed Jun 5, 2019
1 parent 0eb1f85 commit 182ba56
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,9 @@ var user = await GetUser("octocat", "token OAUTH-TOKEN");
#### Authorization (Dynamic Headers redux)
The most common reason to use headers is for authorization. Today most API's use some flavor of oAuth with access tokens that expire and refresh tokens that are longer lived.

One way to encapsulate these kinds of token usage, a custom `HttpClientHandler` can be inserted instead.
One way to encapsulate these kinds of token usage, a custom `HttpClientHandler` can be inserted instead.
There are two classes for doing this: one is `AuthenticatedHttpClientHandler`, which takes a `Func<Task<string>>` parameter, where a signature can be generated without knowing about the request.
The other is `AuthenticatedParameterizedHttpClientHandler`, which takes a `Func<HttpRequestMessage, Task<string>>` parameter, where the signature requires information about the request (see earlier notes about Twitter's API)

For example:
```csharp
Expand Down Expand Up @@ -447,6 +449,34 @@ class AuthenticatedHttpClientHandler : HttpClientHandler
}
```

Or:

```csharp
class AuthenticatedParameterizedHttpClientHandler : DelegatingHandler
{
readonly Func<HttpRequestMessage, Task<string>> getToken;

public AuthenticatedParameterizedHttpClientHandler(Func<HttpRequestMessage, Task<string>> getToken, HttpMessageHandler innerHandler = null)
: base(innerHandler ?? new HttpClientHandler())
{
this.getToken = getToken ?? throw new ArgumentNullException(nameof(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(request).ConfigureAwait(false);
request.Headers.Authorization = new AuthenticationHeaderValue(auth.Scheme, token);
}

return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
}
}
```

While HttpClient contains a nearly identical method signature, it is used differently. HttpClient.SendAsync is not called by Refit. The HttpClientHandler must be modified instead.

This class is used like so (example uses the [ADAL](http://msdn.microsoft.com/en-us/library/azure/jj573266.aspx) library to manage auto-token refresh but the principal holds for Xamarin.Auth or any other library:
Expand Down

0 comments on commit 182ba56

Please sign in to comment.