I have a custom authorization policy where I'd like to output the reason to the output to help the consumer understand why he or she gets a 403 forbidden result. I have the following code:
internal class MyRequirementHandler : AuthorizationHandler<MyRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyRequirement requirement)
{
if (myCondition)
{
context.Succeed(requirement);
}
else
{
context.Fail(new AuthorizationFailureReason(this, "Reason why failing"));
}
return Task.CompletedTask;
}
}
I would expect this to output "Reason why failing" to the body of the response, but I don't. I would get it to work by doing this instead:
if (context.Resource is DefaultHttpContext mvcContext)
{
mvcContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
await mvcContext.HttpContext.Response.WriteAsync("Reason why failing");
}
But that doesn't feel like the correct way.
Grateful for any help and or input!