有条件地忽略对.NET Core 3.1的授权

问题描述 投票:0回答:1

我正在将Web API从.net Framework迁移到.net Core。如果应用程序在私有服务器上运行,则旧版本可以忽略控制器上的Authorize Attribute。这是代码。 我知道.net core 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)我无法将配置中的变量从控制器传递给参数化的授权属性。 2)我无法将配置注入到参数化的授权属性中。

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

这导致我的问题:我如何使用appSettings.json中的值来覆盖请求是否检查角色?

c# .net core ignore authorize
1个回答
0
投票

经过大量研究,我找到了一种使用TypeFilterAttribute的方法。本质上,这是相同的方法(使用自定义属性过滤所有请求并检查自定义属性中的条件),只是我使用了.net Core支持的方法。

如果您要解决同一问题,这是解决方案的确切步骤。

  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. 控制器代码:
[YourAttributeName("role_name")]
[Route("api/my_route")]
[HttpGet]
© www.soinside.com 2019 - 2024. All rights reserved.