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)?
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.
Register health check services with AddHealthChecks in Startup. ConfigureServices . Create a health check endpoint by calling MapHealthChecks in Startup. Configure .
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.
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());
});
Starting with .NET 5 there is a new clearer method for this - AllowAnonymous()
app.UseEndpoints(endpoints =>
{
endpoints.MapHealthChecks("/health").AllowAnonymous();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With