基于Asp.net核心代码的策略需要访问Authorize属性

时间:2016-11-02 12:18:47

标签: security asp.net-core

在我的多租户应用程序中,每个租户设置了用户权限(如果您对此更熟悉,请阅读角色),因此我们向每个用户添加值为 TenantName 的声明:权限

我们正在使用基于策略的授权和自定义代码,使用以下代码

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class PermissionAuthorizeAttribute : AuthorizeAttribute
{
    public Permission[] AcceptedPermissions { get; set; }

    public PermissionAuthorizeAttribute()
    {

    }

    public PermissionAuthorizeAttribute(params Permission[] acceptedPermissions)
    {
        AcceptedPermissions = acceptedPermissions;
        Policy = "RequirePermission";
    }
}

public enum Permission
{
    Login = 1,
    AddUser = 2,
    EditOtherUser = 3,
    EditBaseData = 6,
    EditSettings = 7,
}

使用上面的代码我们装饰Controller动作

[PermissionAuthorize(Permission.EditSettings)]
public IActionResult Index()

在startup.cs中我们有

services.AddAuthorization(options =>
    {
        options.AddPolicy("RequirePermission", policy => policy.Requirements.Add(new PermissionRequirement()));
    });

在这种情况下,AuthorizationHandler需要访问PermissionAuthorizeAttribute,以便我们可以检查在操作上指定了哪些权限。目前我们可以使用下面的代码获取属性,但我认为必须有一个更简单的方法,因为那里有大量的迭代。

public class PermissionRequirement : AuthorizationHandler<PermissionRequirement>, IAuthorizationRequirement
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
    {

        var filters = ((FilterContext)context.Resource).Filters;

        PermissionAuthorizeAttribute permissionRequirement = null;
        foreach (var filter in filters)
        {
            var authorizeFilter = filter as AuthorizeFilter;
            if (authorizeFilter == null || authorizeFilter.AuthorizeData == null)
                continue;

            foreach (var item in authorizeFilter.AuthorizeData)
            {
                permissionRequirement = item as PermissionAuthorizeAttribute;
                if (permissionRequirement != null)
                    break;
            }

            if (permissionRequirement != null)
                break;
        }

        //TODO Check that the user has the required claims

        context.Succeed(requirement);
        return Task.CompletedTask;
    }
}

我发现的所有示例都是这样的,其中在startup.cs中指定了一些硬连线策略。     services.AddAuthorization(options =&gt;     {         options.AddPolicy(&#34; Over21&#34 ;,                           policy =&gt; policy.Requirements.Add(new MinimumAgeRequirement(21)));     }

在这里,您使用

装饰控制器或操作
[Authorize(Policy="Over21")]
public class AlcoholPurchaseRequirementsController : Controller

我认为如果你可以在控制器/动作中指定年龄,上面的例子会更好,比如

[Authorize(Policy="OverAge", Age=21)]
public class AlcoholPurchaseRequirementsController : Controller

现在,您需要为每个最低年龄添加不同的政策。

关于如何提高效率的任何想法?

1 个答案:

答案 0 :(得分:1)

虽然我会像我评论的那样使用Resource Based Authorization,但有一种方法可以实现您的目标:

首先创建一个自定义属性:

public class AgeAuthorizeAttribute : Attribute
{
    public int Age{ get; set; }
    public AgeAuthorizeAttribute(int age)
    {
        Age = age;
    }
}

然后编写过滤器提供程序:

public class CustomFilterProvider : IFilterProvider
{
    public int Order
    {
        get
        {
            return 0;
        }
    }

    public void OnProvidersExecuted(FilterProviderContext context)
    {
    }

    public void OnProvidersExecuting(FilterProviderContext context)
    {
        var ctrl = context.ActionContext.ActionDescriptor as ControllerActionDescriptor;
        var ageAttr = ctrl.MethodInfo.GetCustomAttribute<AgeAuthorizeAttribute>();
        if (ageAttr == null)
        {
             ageAttr = ctrl.ControllerTypeInfo.GetCustomAttribute<AgeAuthorizeAttribute>();
        }
        if (ageAttr != null)
        {
            var policy = new AuthorizationPolicyBuilder()
                   .AddRequirements(new MinimumAgeRequirement(ageAttr.Age))
                   .Build();

            var filter = new AuthorizeFilter(policy);
            context.Results.Add(new FilterItem(new FilterDescriptor(filter, FilterScope.Action), filter));
        }
    }
}

最后注册过滤器提供商:

services.TryAddEnumerable(ServiceDescriptor.Singleton<IFilterProvider, CustomFilterProvider>());

并使用它

[AgeAuthorize(21)]
public IActionResult SomeAction()

... or
[AgeAuthorize(21)]
public class AlcoholPurchaseRequirementsController : Controller

ps:未经测试