refit icon indicating copy to clipboard operation
refit copied to clipboard

Is there any way to implement optional authentication?

Open afunc233 opened this issue 10 months ago • 0 comments

Is your feature request related to a problem? Please describe.

I use this to implementing Bearer authentication

and Server authentication information for the interface is optional

Describe the solution you'd like

Perhaps when the return value is empty, the authentication information can be removed

Describe alternatives you've considered

Of course I can use a custom httpclient with OptionalAuthenticatedHttpClientHandler to achieve this Feature

class OptionalAuthenticatedHttpClientHandler : DelegatingHandler
{
    readonly Func<HttpRequestMessage, CancellationToken, Task<string>> getToken;

    public OptionalAuthenticatedHttpClientHandler(Func<HttpRequestMessage, CancellationToken, 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, cancellationToken).ConfigureAwait(false);
            if (!string.IsNullOrWhiteSpace(token))
            {
                request.Headers.Authorization = new AuthenticationHeaderValue(auth.Scheme, token);
            }
            else
            {
                request.Headers.Authorization = null;
            }
        }

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

Describe suggestions on how to achieve the feature

OptionalAuthenticatedHttpClientHandler

Additional context

Maybe there are other better ways?

afunc233 avatar Apr 25 '24 17:04 afunc233