学海无涯

导航

自定义 AuthorizationMiddleware 的行为

在其它角色、策略权限验证后,系统再执行中间件,中间件成功后,最后才执行调用控制器方法。

其它策略-》授权中间件-》控制器方法

应用可以注册 IAuthorizationMiddlewareResultHandler,以自定义 AuthorizationMiddleware 处理授权结果的方式。 应用可将 IAuthorizationMiddlewareResultHandler 用于:

  • 返回自定义的响应。
  • 增强默认质询或禁止响应。
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization.Policy;
using TestIdentity.Infrastructure.Data;

namespace TestIdentity.Web.CustomIdentity;

public class SampleAuthorizationMiddlewareResultHandler : IAuthorizationMiddlewareResultHandler
{

  AppDbContext dbContext;
  private readonly IAuthorizationMiddlewareResultHandler defaultHandler;

  public SampleAuthorizationMiddlewareResultHandler(AppDbContext dbContext)
  {
    this.dbContext = dbContext;
    this.defaultHandler = new AuthorizationMiddlewareResultHandler();
  }

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


    var project = dbContext.Projects.FirstOrDefault(m => m.Name == "admin");
    if (project == null)
    {
      context.Response.StatusCode = StatusCodes.Status203NonAuthoritative;
      return;
    }

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

  public class Show404Requirement : IAuthorizationRequirement { }
}

  

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

  

posted on 2024-04-18 12:03  宁静致远.  阅读(29)  评论(0编辑  收藏  举报