HttpError401Handler Class

Namespace
Kampute.HttpClient.ErrorHandlers
Assembly
  • Kampute.HttpClient.dll

Definition

Handles '401 Unauthorized' responses by obtaining new authorization and retrying the request with it.
public class HttpError401Handler : IHttpErrorHandler, IDisposable
Inheritance
Implements

Remarks

When a request receives a '401 Unauthorized' response, the handler calls the authentication function passed to its constructor, sets the authorization it returns as the Authorization header of HttpRestClient.DefaultRequestHeaders, and retries the request with it. The handler retries a call once: if the retry is also rejected, the response reaches the caller as an HttpResponseException. It does not retry a request whose content cannot be sent again, such as a StreamContent over a non-seekable stream, and does not call the function for it.

When several requests are rejected at the same time, the function runs once and all of them retry with its result. A request that was rejected with older authorization than the latest one the handler obtained is retried with the latest one, without calling the function.

One instance can serve several clients that use the same credentials. Keep it alive while the clients use it, and dispose it afterwards.

Examples

This handler obtains a new access token when a request is rejected. RefreshAccessTokenAsync stands for the application's own code that requests a token from its authentication service.
using var unauthorizedHandler = new HttpError401Handler(async (ctx, cancellationToken) =>
{
    var token = await RefreshAccessTokenAsync(cancellationToken);
    return new AuthenticationHeaderValue(AuthSchemes.Bearer, token);
});

client.ErrorHandlers.Add(unauthorizedHandler);

Constructors

HttpError401Handler(Func<HttpResponseErrorContext, CancellationToken, Task<AuthenticationHeaderValue>>)

Initializes a new instance of the HttpError401Handler class.
public HttpError401Handler(Func<HttpResponseErrorContext, CancellationToken, Task<AuthenticationHeaderValue>> asyncAuthenticator)

Parameters

asyncAuthenticator Func<HttpResponseErrorContext, CancellationToken, Task<AuthenticationHeaderValue>>
The function that obtains new authorization. It receives the context of the '401 Unauthorized' response and a cancellation token, and returns the AuthenticationHeaderValue to send, or null if authentication fails, in which case the request is not retried. Requests that the function sends with the same client are not handled by this handler, so a rejected token request cannot wait on itself.

Exceptions

ArgumentNullException
Thrown if asyncAuthenticator is null.

Methods

AuthenticateAsync(HttpResponseErrorContext, CancellationToken)

Returns the authorization to retry a rejected request with.
protected virtual Task<AuthenticationHeaderValue> AuthenticateAsync(HttpResponseErrorContext ctx, CancellationToken cancellationToken)

Parameters

ctx HttpResponseErrorContext
The context of the '401 Unauthorized' response.
cancellationToken CancellationToken
A token for canceling the operation.

Returns

Task<AuthenticationHeaderValue>
A task that resolves to the authorization to send, or to null if authentication failed.

Exceptions

ArgumentNullException
Thrown if ctx is null.

Remarks

If the request was sent with authorization other than the latest one the handler obtained, this method returns the latest one without calling the authentication function. Otherwise, it calls the function, or waits for a call already in progress.

CanHandle(HttpStatusCode)

Determines whether this handler can process the specified HTTP status code.
public bool CanHandle(HttpStatusCode statusCode)

Parameters

statusCode HttpStatusCode
The HTTP status code to evaluate.

Returns

bool
true if statusCode is '401 Unauthorized'; otherwise, false.

Dispose()

Releases the resources that the handler uses to coordinate concurrent authentication.
public void Dispose()

Explicit Interface Implementations

IHttpErrorHandler.DecideOnRetryAsync(HttpResponseErrorContext, CancellationToken)

Decides whether to retry a request after an error response.
Task<HttpErrorHandlerResult> IHttpErrorHandler.DecideOnRetryAsync(HttpResponseErrorContext ctx, CancellationToken cancellationToken)

Parameters

ctx HttpResponseErrorContext
The context containing information about the HTTP response that indicates a failure.
cancellationToken CancellationToken
A token for canceling the operation.

Returns

Task<HttpErrorHandlerResult>
A task that resolves to HttpErrorHandlerResult.Retry(HttpRequestMessage) with the request to send, or to HttpErrorHandlerResult.NoRetry to let the next handler decide.

Exceptions

ArgumentNullException
Thrown if ctx is null.

See Also