Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is there any way to implement optional authentication? #1688

Open
afunc233 opened this issue Apr 25, 2024 · 0 comments
Open

Is there any way to implement optional authentication? #1688

afunc233 opened this issue Apr 25, 2024 · 0 comments
Labels

Comments

@afunc233
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants