Het gedrag van autorisatie-middleware aanpassen

Apps kunnen een IAuthorizationMiddlewareResultHandler registreren om aan te passen hoe AuthorizationMiddleware autorisatieresultaten worden verwerkt. Apps kunnen het volgende gebruiken IAuthorizationMiddlewareResultHandler :

  • Aangepaste antwoorden retourneren.
  • Verbeter de standaardvraag of verbood antwoorden.

De volgende code toont een voorbeeld van een implementatie van IAuthorizationMiddlewareResultHandler die een aangepast antwoord retourneert voor specifieke autorisatiefouten:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Policy;

public class SampleAuthorizationMiddlewareResultHandler : IAuthorizationMiddlewareResultHandler
{
    private readonly AuthorizationMiddlewareResultHandler defaultHandler = new();

    public async Task HandleAsync(
        RequestDelegate next,
        HttpContext context,
        AuthorizationPolicy policy,
        PolicyAuthorizationResult authorizeResult)
    {
        // If the authorization was forbidden and the resource had a specific requirement,
        // provide a custom 404 response.
        if (authorizeResult.Forbidden
            && authorizeResult.AuthorizationFailure!.FailedRequirements
                .OfType<Show404Requirement>().Any())
        {
            // Return a 404 to make it appear as if the resource doesn't exist.
            context.Response.StatusCode = StatusCodes.Status404NotFound;
            return;
        }

        // Fall back to the default implementation.
        await defaultHandler.HandleAsync(next, context, policy, authorizeResult);
    }
}

public class Show404Requirement : IAuthorizationRequirement { }

Registreer deze implementatie IAuthorizationMiddlewareResultHandler in Program.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<
    IAuthorizationMiddlewareResultHandler, SampleAuthorizationMiddlewareResultHandler>();

var app = builder.Build();