AzureAD / microsoft-identity-web

Helps creating protected web apps and web APIs with Microsoft identity platform and Azure AD B2C
MIT License
673 stars 208 forks source link

Configure HttpClient of DownstreamApi in order to set custom timeout for Http requests #2378

Open serhatataman opened 1 year ago

serhatataman commented 1 year ago

I have multiple microservices that have cold-start about 20+ seconds. My requests through DownstreamApi return 502 Bad Gateway when sending a requests.

I would love to be able to configure HttpClient of DownstreamApi, so that I can set up a timeout value of 30 seconds.

AndreErb commented 1 year ago

We achieve this by adding a "HttpClient" to the ServiceCollection with the Service name, used in "AddDownstreamApi"

by extension method:

public static MicrosoftIdentityAppCallsWebApiAuthenticationBuilder UseHttpClientTimeout(this MicrosoftIdentityAppCallsWebApiAuthenticationBuilder builder, string serviceName, TimeSpan timeout) 
{ 
    builder.Services.AddHttpClient(serviceName, client =>
    {
      client.Timeout = timeout;
    });
    return builder;
 }

and then used like

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(configuration.GetSection("AzureAd"))
        .EnableTokenAcquisitionToCallDownstreamApi(initialScopes).
.AddDownstreamApi("MyService", configuration.GetSection("MyApi"))
.UseHttpClientTimeout("MyService", TimeSpan.FromMinutes(1))