Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow anonymouos access to healthcheck endpoint when authentication fallback policy is set in ASP.NET Core 3

asp.net core 3 allows to set FallbackPolicy to make the endpoints secure by default:

            services.AddAuthorization(options =>
            {
                options.FallbackPolicy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
            });

It is a great feature, but I have a HealthCheck endpoint too, that requires Authorization now.

            services.AddHealthChecks();
            [...]
            app.UseEndpoints(endpoints => {
                endpoints.MapHealthChecks("/health");
                endpoints.MapControllers();
            });

How do I allow anonymous access to the HealthCheck endpoint (NO authentication or authorization)?

like image 870
wxt Avatar asked Dec 18 '19 08:12

wxt


People also ask

What is the fallback policy method that is used to require users to be authenticated?

The Default Policy is the policy that gets evaluated when authorization is required, but no explicit policy is specified. In other words, it's the policy that evaluates when you add an [Authorize] attribute without any PolicyName. Out of the box, the Default Policy is set to requiring Authenticated Users.

How would you add a health check on an ASP NET core API project you are working on?

Register health check services with AddHealthChecks in Startup. ConfigureServices . Create a health check endpoint by calling MapHealthChecks in Startup. Configure .

What is services AddHealthChecks?

In the previous code, the services. AddHealthChecks() method configures a basic HTTP check that returns a status code 200 with "Healthy". Further, the AddCheck() extension method configures a custom SqlConnectionHealthCheck that checks the related SQL Database's health.


2 Answers

I ran into exactly the same issue so I hope this helps as a more satisfactory way of achieving:

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute().RequireAuthorization();

            endpoints.MapHealthChecks("/health").WithMetadata(new AllowAnonymousAttribute());

        });
like image 188
Michael Gregson Avatar answered Oct 11 '22 12:10

Michael Gregson


Starting with .NET 5 there is a new clearer method for this - AllowAnonymous()

app.UseEndpoints(endpoints =>
    {
        endpoints.MapHealthChecks("/health").AllowAnonymous();
    });
like image 22
Felix Avatar answered Oct 11 '22 14:10

Felix