簡體   English   中英

有條件忽略授權 .NET Core 3.1

[英]Conditionally Ignore Authorize .NET Core 3.1

我正在將 web API 從 Z2D50972FECD376129545507F1062089Z 框架遷移到 Z2D50972FECD376129545507FZ 內核。 如果應用程序在私有服務器上運行,舊版本能夠忽略 controller 上的授權屬性。 這是代碼。 我知道 .net 核心 3.1 不提供自定義 AuthorizeAttributes。 那不是我的問題。

// A custom AuthroizeAttribute
public class ConditionalAuthorizeAttribute : AuthorizeAttribute
{

    protected override bool IsAuthorized(HttpActionContext httpContext)
    {
        if (environment_private())
            return true;
        else
            return base.IsAuthorized(httpContext);
    }


    private bool environment_private()
    {
        // code that will tell you if you are in your dev environment or not
        return Properties.Settings.Default.PrivateServer;
    }
}

// How it was called from the controller
[ConditionalAuthorize(Roles = "MyRole")]
[Route(...)]
// More code for controller

在我們的私有服務器上運行項目時,我只需要一種簡單的方法來授權所有請求(由 appSettings.json 中的變量確定)。 我嘗試過政策,但我面臨以下困難:

1) 我無法將配置中的變量從 controller 傳遞給參數化授權屬性。
2) 我無法將配置注入參數化授權屬性。

這有效地消除了我以任何方式遵循本指南的能力: https://docs.microsoft.com/en-us/aspnet/core/security/authorization/iauthorizationpolicyprovider?view=aspnetcore-2.2

這引出了我的問題:如何使用 appSettings.json 中的值來覆蓋請求是否檢查角色?

經過大量研究,我找到了一種使用TypeFilterAttribute的方法。 本質上,這是相同的方法(使用自定義屬性過濾所有請求並檢查自定義屬性中的條件),除了我使用了 .net 核心支持的方法。

如果您嘗試解決同樣的問題,以下是我的解決方案的確切步驟。

  1. 添加兩個文件,“YourAttributeNameAttribute.cs”和“YourFilterNameFilter.cs”。
  2. 在“YourAttributeNameAttribute.cs”文件中,代碼如下:
public class YourAttributeNameAttribute : TypeFilterAttribute
{
    public YourAttributeNameAttribute(string role) : base(typeof(YourFilterNameFilter))
    {
        Arguments = new object[] { role };
    }
}
  1. “YourFilterNameFilter.cs”中的代碼:
public class YourFilterNameFilter : IAuthorizationFilter
{
    private readonly string Role;
    public YourFilterNameFilter(string role)
    {
        Role = role;
    }
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var configuration = context.HttpContext.RequestServices.GetService<IConfiguration>();

        // If private server, ignore roles
        if (private_server_logic_here)
            return;

        var user = context.HttpContext.User;

        // Check role if on public server
        if (!user.IsInRole(Role))
        {
            context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.Unauthorized);
            return;
        }
    }
}
  1. controller 的代碼:
[YourAttributeName("role_name")]
[Route("api/my_route")]
[HttpGet]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM