다음을 통해 공유


AuthorizationMiddleware의 동작을 사용자 지정

앱은 IAuthorizationMiddlewareResultHandler를 등록하여 AuthorizationMiddleware가 권한 부여 결과를 처리하는 방법을 사용자 지정할 수 있습니다. 앱은 IAuthorizationMiddlewareResultHandler를 사용하여 다음을 수행할 수 있습니다.

  • 사용자 지정된 응답을 반환합니다.
  • 기본 챌린지를 개선하거나 응답을 금지합니다.

다음 코드는 특정 권한 부여 실패에 대한 사용자 지정 응답을 반환하는 IAuthorizationMiddlewareResultHandler 구현 예제를 보여 줍니다.

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 { }

Program.cs에서 IAuthorizationMiddlewareResultHandler가 구현을 등록합니다.

var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();

앱은 IAuthorizationMiddlewareResultHandler를 등록하여 AuthorizationMiddleware가 권한 부여 결과를 처리하는 방법을 사용자 지정할 수 있습니다. 앱은 IAuthorizationMiddlewareResultHandler를 사용하여 다음을 수행할 수 있습니다.

  • 사용자 지정된 응답을 반환합니다.
  • 기본 챌린지를 개선하거나 응답을 금지합니다.

다음 코드는 특정 권한 부여 실패에 대한 사용자 지정 응답을 반환하는 IAuthorizationMiddlewareResultHandler 구현 예제를 보여 줍니다.

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Policy;
using Microsoft.AspNetCore.Http;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

public class MyAuthorizationMiddlewareResultHandler : IAuthorizationMiddlewareResultHandler
{
   private readonly AuthorizationMiddlewareResultHandler 
        DefaultHandler = new AuthorizationMiddlewareResultHandler();
    
    public async Task HandleAsync(
        RequestDelegate requestDelegate,
        HttpContext httpContext,
        AuthorizationPolicy authorizationPolicy,
        PolicyAuthorizationResult policyAuthorizationResult)
    {
        // if the authorization was forbidden and the resource had specific requirements,
        // provide a custom response.
        if (Show404ForForbiddenResult(policyAuthorizationResult))
        {
            // Return a 404 to make it appear as if the resource does not exist.
            httpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
            return;
        }

        // Fallback to the default implementation.
        await DefaultHandler.HandleAsync(requestDelegate, httpContext, authorizationPolicy, 
                               policyAuthorizationResult);
    }

    bool Show404ForForbiddenResult(PolicyAuthorizationResult policyAuthorizationResult)
    {
        return policyAuthorizationResult.Forbidden &&
            policyAuthorizationResult.AuthorizationFailure.FailedRequirements.OfType<
                                                           Show404Requirement>().Any();
    }
}

public class Show404Requirement : IAuthorizationRequirement { }

Startup.ConfigureServicesMyAuthorizationMiddlewareResultHandler 등록:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddSingleton<IAuthorizationMiddlewareResultHandler,
                          MyAuthorizationMiddlewareResultHandler>();
}