question

AshutoshPareek-3300 avatar image
0 Votes"
AshutoshPareek-3300 asked RenaNi-MSFT commented

How to do Authorization for UseHealthCheck middleware

For health check I am using UseHealthChecks middleware extension where I am setting path argument to /hc.
How can add or remove authorization here based on config?

I want to achieve similar to below code with UseHealthChecks where I can add or remove RequireAuthorization based on condition.

app.UseEndpoints(endpoints =>
{
    endpoints.MapHealthChecks("/health").RequireAuthorization();
});



dotnet-csharpdotnet-aspnet-core-generaldotnet-aspnet-core-webapi
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Bruce-SqlWork avatar image
0 Votes"
Bruce-SqlWork answered RenaNi-MSFT commented

Use an if statement

 app.UseEndpoints(endpoints =>
 {
     var ep = endpoints.MapHealthChecks("/health");
      if (UseHealtChecks) 
           ep.RequireAuthorization();
 });
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @AshutoshPareek-3300 , Did you try this: app.MapWhen(context => context.Request.Method == HttpMethod.Get.Method &&context.Request.Path.StartsWithSegments("/health"),builder => builder.UseHealthChecks("/health").UseAuthentication()); refer to this document: https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-5.0#restrict-health-checks-with-mapwhen

1 Vote 1 ·