Advertisement
Advanced ASP.NET Core, Authorization

How does the AuthorizationMiddlewareResultHandler let you customize the response returned when authorization fails, beyond the default 401/403?

Short answer

Implementing a custom IAuthorizationMiddlewareResultHandler and registering it lets you intercept authorization failures to return a custom response shape (like a ProblemDetails-formatted JSON error explaining exactly which policy failed) instead of the framework's bare default…

Save ASP.NET Core mock interview
Advertisement
AModel answer
Implementing a custom IAuthorizationMiddlewareResultHandler and registering it lets you intercept authorization failures to return a custom response shape (like a ProblemDetails-formatted JSON error explaining exactly which policy failed) instead of the framework's bare default response, useful for APIs wanting consistent, informative error responses across every kind of failure including authorization.
public class CustomAuthResultHandler : IAuthorizationMiddlewareResultHandler {
    private readonly AuthorizationMiddlewareResultHandler _default = new();
    public async Task HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult) {
        if (!authorizeResult.Succeeded) {
            context.Response.StatusCode = 403;
            await context.Response.WriteAsJsonAsync(new { title = "Access denied", policy = policy.AuthenticationSchemes });
            return;
        }
        await _default.HandleAsync(next, context, policy, authorizeResult);
    }
}

builder.Services.AddSingleton<IAuthorizationMiddlewareResultHandler, CustomAuthResultHandler>();
Real-world example
An API standardizing all error responses (including authorization failures) on the ProblemDetails format registers a custom result handler so a failed policy check produces the same consistent JSON error shape as any other error type in the application.
Likely follow-ups
  • How does this interact with the global exception handling middleware for other error types?
  • What's the risk of leaking too much detail about why authorization failed?
Related topics