Ping test should be relatively simple, there are currently several possibilities to prevent such url from anonymous access, like policies or action filters.
Policy-based authorization
Let's create a simple policy that requires a Secret key in the query string.
First, create the requirement with handler e.g.:
public class HasSecretKeyRequirement : IAuthorizationRequirement
{
}
public class HasSecretKeyRequirementHandler : AuthorizationHandler<HasSecretKeyRequirement>
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IConfiguration _configuration;
public HasSecretKeyRequirementHandler(IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
{
_httpContextAccessor = httpContextAccessor;
_configuration = configuration;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasApiKeyRequirement requirement)
{
var httpContext = _httpContextAccessor.HttpContext;
if (httpContext == null)
{
context.Fail();
return Task.CompletedTask;
}
if (httpContext.Request.Query.TryGetValue("SecretKey", out extractedSecretKey))
{
var secretKey= _configuration.GetValue<string>("SecretKey");
if (secretKey.Equals(extractedSecretKey))
{
context.Succeed(requirement);
return Task.CompletedTask;
}
}
httpContext.Response.ContentType = "text/plain";
httpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
context.Fail();
return Task.CompletedTask;
}
}
Then create a new policy with requirement and register requirement handler:
services.AddAuthorization(options =>
{
options.AddPolicy("HasSecretKey", policy =>
policy.Requirements.Add(new HasSecretKeyRequirement()));
);
services.AddSingleton<IAuthorizationHandler, HasSecretKeyRequirementHandler>();
Apply policy to your ping endpoint:
[Authorize(Policy = "HasSecretKey")]
[HttpGet("api/ping")]
public IActionResult Ping()
{
return Ok();
}
Finallddd configure your availability test:
https://yourapi.com/api/ping?SecretKey=yoursecretkey
This is just an example, you can create your own requirement and handling logic. You can reuse these policies in your application, e.g. in the healthcheck endpoint:
endpoints.MapHealthChecks("/health")
.RequireAuthorization("HasSecretKey");
This form of authorization may be sufficient in such a simple case, but definitely should not be used in more advanced scenarios.