damienbod / AspNetCoreExperiments

ASP.NET Core Blazor BFF with Microsoft Entra ID and Razor page
https://damienbod.com/2021/06/28/sign-in-using-multiple-clients-or-tenants-in-asp-net-core-and-azure-ad/
MIT License
50 stars 6 forks source link

Can you use this.jSRuntime.InvokeAsync inside DelegatingHandler? #21

Open VictorioBerra opened 1 year ago

VictorioBerra commented 1 year ago

I want to add a typed client here https://github.com/damienbod/AspNetCoreExperiments/blob/main/BlazorBffAzureADWithApi/Client/Program.cs#L25

But I cant because my clients must be created with IAntiforgeryHttpClientFactory so that IJSRuntime can work.

Would it work to use DelegatingHandler instead and that way any typed clients inherit that ability?

IE:

builder.Services
  .AddHttpClient("authorizedClient", client =>
  {
      client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  })
  .AddTypedClient<IGitHubAPIClient>() // Will not pass antiforgery token!!! Must be created with IAntiforgeryHttpClientFactory!!! <---------
  .AddHttpMessageHandler<AuthorizedHandler>();

builder.Services.AddTransient(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("default"));
builder.Services.AddTransient<IAntiforgeryHttpClientFactory, AntiforgeryHttpClientFactory>();
damienbod commented 1 year ago

@VictorioBerra I would need to test this, don't know :)

FYI You could also use a HTTP custom header instead of anti-forgery tokens to protect against this threat as well. Validate this on the backend. (forces preflight requests)

Interested if you find a solution.

Greetings Damien