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)?
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());
});
You could invoke the HealthCheckMiddleware before using the AuthenticationMiddleware:
app.Map("/health",appbuilder =>{
appbuilder.UseMiddleware<HealthCheckMiddleware>();
});
// or
// app.UseHealthChecks("/health");
app.UseRouting();
// make sure the authentication middleware runs after the health check middleware
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});