Reputation: 1950
When using an Authorization Policy is it possible to understand which policy did not succeed?
Ideally I'd like to be able to modify the data within the middleware pipeline to better identify why a 403 is being returned to the API consumer.
All that is returned at the moment is a 403; Forbidden.
[Authorize] // Azure auth
[Authorize(Policy="SessionIsValid")] // Ensure transaction sessions are valid
public class TaskController : Controller
{ /** code removed for brevity */ }
Is it possible to understand the reason for the failed policy with in the configure method of Statup.cs?
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 403 )
{
// which policy failed? need to inform consumer which requirement was not met
await next()
}
});
Upvotes: 3
Views: 782
Reputation: 1998
FYI, the .Resource
was unavailable for me in Minimal Apis (or I couldn't find it).
https://benfoster.io/blog/customize-authorization-response-aspnet-core/
Works for me to implement a IAuthorizationMiddlewareResultHandler
object.
Upvotes: 0
Reputation: 1950
From ASPNET Core Docs
The use of the Resource property is framework specific. Using information in the Resource property will limit your authorization policies to particular frameworks. You should cast the Resource property using the as keyword, and then check the cast has succeed to ensure your code doesn't crash with InvalidCastExceptions when run on other frameworks;
My Implementation
context.Fail();
if ( context.Resource is Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext mvcContext) {
mvcContext.HttpContext.Response.StatusCode = 403;
await mvcContext.HttpContext.Response.WriteAsync($"Forbidden; No valid Transaction Session Id for {context.User.Identity.Name}");
}
Upvotes: 3