C# 有条件地忽略授权.NET Core 3.1

C# 有条件地忽略授权.NET Core 3.1,c#,.net,core,ignore,authorize,C#,.net,Core,Ignore,Authorize,我正在将web API从.net Framework迁移到.net Core。如果应用程序在专用服务器上运行,则旧版本可以忽略控制器上的Authorize属性。这是代码我知道.net core 3.1不提供自定义属性。这不是我的问题。 // A custom AuthroizeAttribute public class ConditionalAuthorizeAttribute : AuthorizeAttribute { protected override bool IsAuth

我正在将web API从.net Framework迁移到.net Core。如果应用程序在专用服务器上运行,则旧版本可以忽略控制器上的Authorize属性。这是代码我知道.net core 3.1不提供自定义属性。这不是我的问题。

// 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) 我无法将配置中的变量从控制器传递到参数化的authorize属性。
2) 我无法将配置注入参数化的authorize属性

这实际上消除了我以任何方式遵循本指南的能力:


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

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

如果您试图解决同一问题,以下是我的解决方案的确切步骤

  • 添加两个文件,“YourAttributeNameAttribute.cs”和“YourFilterNameFilter.cs”
  • 在“YourAttributeNameAttribute.cs”文件中,代码如下所示:
  • “YourFilterNameFilter.cs”中的代码:
  • public class YourAttributeNameAttribute : TypeFilterAttribute
    {
        public YourAttributeNameAttribute(string role) : base(typeof(YourFilterNameFilter))
        {
            Arguments = new object[] { role };
        }
    }
    
    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;
            }
        }
    }
    
    [YourAttributeName("role_name")]
    [Route("api/my_route")]
    [HttpGet]