方法上的多个授权属性

时间:2013-06-24 09:43:00

标签: c# asp.net-mvc

我在类方法上指定两个单独的Authorization属性时遇到问题:如果两个属性中的任何一个为真,则允许用户访问。

Athorization类看起来像这样:

[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
public class AuthAttribute : AuthorizeAttribute {
. . .

和行动:

[Auth(Roles = AuthRole.SuperAdministrator)]
[Auth(Roles = AuthRole.Administrator, Module = ModuleID.SomeModule)]
public ActionResult Index() {
    return View(GetIndexViewModel());
}

有没有办法解决这个问题,还是我需要重新考虑我的方法?

这将在MVC2中运行。

4 个答案:

答案 0 :(得分:39)

在更高版本的asp.net中有更好的方法可以在角色上同时执行OR和AND。这是通过约定完成的,在单个Authorize中列出多个角色将执行OR,其中添加多个授权属性将执行AND。

OR示例

[Authorize(Roles = "PowerUser,ControlPanelUser")] 

AND示例

[Authorize(Roles = "PowerUser")]
[Authorize(Roles = "ControlPanelUser")]

您可以在以下链接中找到有关此内容的更多信息 https://docs.microsoft.com/en-us/aspnet/core/security/authorization/roles

答案 1 :(得分:29)

MVC会处理多个AuthorizeAttribute实例,就像它们与AND一起加入一样。如果您想要OR行为,则需要实现自己的检查逻辑。最好实现AuthAttribute以承担多个角色并使用OR逻辑执行自己的检查。

另一个解决方案是使用标准AuthorizeAttribute并实现自定义IPrincipal,它将实现bool IsInRole(string role)方法以提供“OR”行为。

这里有一个例子: https://stackoverflow.com/a/10754108/449906

答案 2 :(得分:2)

我已经在生产环境中使用.NET Core 3.0了一段时间了。我希望在自定义属性和本机AuthorizeAttribute之间进行“或”操作。为此,我实现了IAuthorizationEvaluator接口,所有授权者对其结果进行评估后就会被调用

/// <summary>
/// Responsible for evaluating if authorization was successful or not, after execution of
/// authorization handler pipelines.
/// This class was implemented because MVC default behavior is to apply an AND behavior
/// with the result of each authorization handler. But to allow our API to have multiple
/// authorization handlers, in which the final authorization result is if ANY handlers return
/// true, the class <cref name="IAuthorizationEvaluator" /> had to be extended to add this
/// OR behavior.
/// </summary>
public class CustomAuthorizationEvaluator : IAuthorizationEvaluator
{
    /// <summary>
    /// Evaluates the results of all authorization handlers called in the pipeline.
    /// Will fail if: at least ONE authorization handler calls context.Fail() OR none of
    /// authorization handlers call context.Success().
    /// Will succeed if: at least one authorization handler calls context.Success().
    /// </summary>
    /// <param name="context">Shared context among handlers.</param>
    /// <returns>Authorization result.</returns>
    public AuthorizationResult Evaluate(AuthorizationHandlerContext context)
    {
        // If context.Fail() got called in ANY of the authorization handlers:
        if (context.HasFailed == true)
        {
            return AuthorizationResult.Failed(AuthorizationFailure.ExplicitFail());
        }

        // If none handler called context.Fail(), some of them could have called
        // context.Success(). MVC treats the context.HasSucceeded with an AND behavior,
        // meaning that if one of the custom authorization handlers have called 
        // context.Success() and others didn't, the property context.HasSucceeded will be
        // false. Thus, this class is responsible for applying the OR behavior instead of
        // the default AND.

        bool success = 
            context.PendingRequirements.Count() < context.Requirements.Count();

        return success == true 
            ? AuthorizationResult.Success()
            : AuthorizationResult.Failed(AuthorizationFailure.ExplicitFail());
    }
}

仅当按如下方式将其添加到.NET服务集合(在您的启动类中)时,才会调用此评估器:

services.AddSingleton<IAuthorizationEvaluator, CustomAuthorizationEvaluator>();

在控制器类中,用两个属性装饰每个方法。就我而言,[Authorize][CustomAuthorize]

答案 3 :(得分:0)

我不确定其他人对此有何看法,但我也想要一种OR的举止。在我的AuthorizationHandler中,只要其中任何一个通过,我就给Succeed打电话。请注意,这不适用于没有参数的内置Authorize属性。

public class LoggedInHandler : AuthorizationHandler<LoggedInAuthReq>
{
    private readonly IHttpContextAccessor httpContextAccessor;
    public LoggedInHandler(IHttpContextAccessor httpContextAccessor)
    {
        this.httpContextAccessor = httpContextAccessor;
    }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, LoggedInAuthReq requirement)
    {
        var httpContext = httpContextAccessor.HttpContext;
        if (httpContext != null && requirement.IsLoggedIn())
        {
            context.Succeed(requirement);
            foreach (var req in context.Requirements)
            {
                context.Succeed(req);
            }
        }

        return Task.CompletedTask;
    }
}

提供您自己的LoggedInAuthReq。在启动时将这些注入服务中

        services.AddAuthorization(o => {
            o.AddPolicy("AadLoggedIn", policy => policy.AddRequirements(new LoggedInAuthReq()));
            ... more here
        });
        services.AddSingleton<IAuthorizationHandler, LoggedInHandler>();
        ... more here

在您的控制器方法中

    [Authorize("FacebookLoggedIn")]
    [Authorize("MsaLoggedIn")]
    [Authorize("AadLoggedIn")]
    [HttpGet("anyuser")]
    public JsonResult AnyUser()
    {
        return new JsonResult(new { I = "did it with Any User!" })
        {
            StatusCode = (int)HttpStatusCode.OK,
        };
    }

这可能也可以通过单个属性和一堆if语句来完成。在这种情况下为works for me。截至撰写本文时,asp.net core 2.2。