Asp.net

使用 aspnet 核心自定義授權過濾器

  • December 23, 2016

您好我正在嘗試創建一個自定義授權過濾器,它允許我自動授權來自本地主機的請求(將用於我的測試)。

我為 Asp.net 找到了以下一個,但是在將其移植到 asp.net 核心時遇到了麻煩。

public class MyAuthorizeAttribute : AuthorizeAttribute
{
   protected override bool AuthorizeCore(HttpContextBase httpContext)
   {
       if (httpContext.Request.Url.IsLoopback)
       {
           // It was a local request => authorize the guy
           return true;
       }

       return base.AuthorizeCore(httpContext);
   }
}

如何將其移植到 asp.net 核心?

您可以創建一個中間件,您可以在其中自動授權來自 localhost 的請求。

public class MyAuthorize
{
  private readonly RequestDelegate _next;
  public MyAuthorize(RequestDelegate next)
  {
     _next = next;
  }

  public async Task Invoke(HttpContext httpContext)
  {
    // authorize request source here.

   await _next(httpContext);
  }
}

然後創建一個擴展方法

public static class CustomMiddleware
{
       public static IApplicationBuilder UseMyAuthorize(this IApplicationBuilder builder)
       {
           return builder.UseMiddleware<MyAuthorize>();
       }
}

最後將其添加到啟動Configure方法中。

app.UseMyAuthorize();

Asp.Net Core 沒有IsLoopback屬性。這是解決此問題的方法 https://stackoverflow.com/a/41242493/2337983

您還可以在此處閱讀有關中間件的更多資訊

引用自:https://stackoverflow.com/questions/41293420