Search code examples
c#asp.netuser-agenthealth-check

How to check user-agent in ASP.NET Core health check calls when using own authentication, authorization?


I used the accepted answer to How to check user-agent in ASP.NET Core health check calls (MapHealthChecks)? , with one difference in requirement:

My application is not using App services authentication and authorization. Therefore, I needed to allow anonymous access for healthcheck as per documentation.

Here are changes to Startup.cs

             //other services

            services.AddHttpContextAccessor();
            services.AddScoped<IAuthorizationHandler, UserAgentAuthorizationHandler>();
            services.AddHealthChecks()
                .AddCheck<HealthCheckFoo>("health_check_foo")
                .AddCheck<HealthCheckBar>("health_check_bar");

             //other  services.AddAuthorization
            
            services.AddAuthorization(options =>
            {
                options.AddPolicy("HealthCheckPolicy", builder =>
                {
                    builder.AddRequirements(new UserAgentRequirement("HealthCheck/1.0"));
                });
            });

            //...
            
            app.UseEndpoints(endpoints =>
             {
                 //other endpoints...

                endpoints.MapHealthChecks("/health", new HealthCheckOptions { AllowCachingResponses = false })
                         .RequireAuthorization("HealthCheckPolicy");
                         .WithMetadata(new AllowAnonymousAttribute());

My expectation is that when testing locally, https://localhost:5001/health return an error. It does not.


Solution

  • It looks as your startup class has a mistake on the endpoints.MapHealthChecks adds a RequireAuthorization but as the same time you also add the AllowAnonymousAttribute.

    Try with:

    app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHealthChecks("/health", new HealthCheckOptions()
                    {
                        AllowCachingResponses = false,
                    })
                    .RequireAuthorization("HealthCheckPolicy");
            });