twitchax / AspNetCore.Proxy

ASP.NET Core Proxies made easy.
MIT License
525 stars 83 forks source link

Possible to use with a configured HttpClientHandler ? #42

Closed szalapski closed 4 years ago

szalapski commented 4 years ago

I'd like to use the proxy to call an endpoint that requires certificate validation.

In ordinary code, I'd write:

    using var handler = new HttpClientHandler() {
        ServerCertificateCustomValidationCallback = ValidateCertificate,
        UseDefaultCredentials = true
    };
    using var httpClient = new HttpClient(handler);
    return await httpClient.GetAsync(url);

with

private static bool ValidateCertificate(
    HttpRequestMessage request, X509Certificate2 certificate, 
    X509Chain certificateChain, SslPolicyErrors policy) { ... }

Any idea how I'd set up an app.UseProxies(proxies => ...) configuration to use a "custom handler" such as above?

szalapski commented 4 years ago

I think I figured it out. I use a named HttpClient, which your code will use if I configure it right.

services
    .AddHttpClient("myClientName")
    .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler() {
        ServerCertificateCustomValidationCallback = ValidateCertificate,
        UseDefaultCredentials = true
    });
proxies.Map(
    "/api/v1/...", 
    proxy => proxy.UseHttp( 
        (context, args) => ...,
        builder => builder.WithHttpClientName("myClientName")));

Is this the way you would do it? Should this be in the README? Or is there a better way?

twitchax commented 4 years ago

Yes, that is exactly how I would do it.

I will leave this open to track adding to README. Thanks!

szalapski commented 4 years ago

PR #44 is up.