自定义授权属性不覆盖/组合特定操作

时间:2017-09-20 15:42:36

标签: c# asp.net-mvc security authorize-attribute

我创建了一个自定义authorize属性,允许进行一些自定义检查以确定整个应用程序的访问权限。

在控制器级别应用自定义auth属性,然后尝试添加对特定操作的其他访问权限时,角色不会以“添加”方式应用。

自定义授权属性:

// Allow multiple = true so should roll all occurrences in a request into one
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class CustomAuthoriseAttribute : AuthorizeAttribute
{
    public CustomAuthoriseAttribute(params string[] roles)
    {
        this.Roles = string.Join(",", roles);
    }

    /// <summary>
    /// Custom routines to determine if a request is considered authorised.
    /// </summary>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
        {
            throw new ArgumentNullException("httpContext");
        }

        var userManager = httpContext.GetOwinContext().GetUserManager<UserManager>();

        var user = userManager.FindById(httpContext.User.Identity.GetUserId());

        if (user == null)
        {
            return false;
        }

        // Log the user out as they should not be allowed access
        if (user.IsDisabled || user.IsDeleted)
        {
            httpContext.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            httpContext.Session.Clear();

            return false;
        }

        return base.AuthorizeCore(httpContext);
    }
}

控制器中的用法:

似乎正在对SuperAdmin和Admin进行auth检查,然后单独检查Consultant,导致未经授权的请求。他们为什么不被完全对待?

[CustomAuthorise(SuperAdministrator, Administrator)]
public class SomeController : Controller
{
    public const string SuperAdministrator = "SuperAdministrator";
    public const string Administrator = "Administrator";
    public const string Consultant = "Consultant";

    // Should only accessible by SuperAdministrators and Administrators
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }

    // Should be accessible by SuperAdministrators, Administrators and Consultants
    [HttpGet]
    [CustomAuthorise(Consultant)]
    public ActionResult SomeAction()
    {
        return View();
    }
}

1 个答案:

答案 0 :(得分:0)

使用逻辑AND处理多个授权属性。每个属性的结果与之前的AND'd。在这种情况下,SomeAction只能由超级管理员或管理员(基于控制器级别属性)访问,并且他们是顾问(基于操作级别属性)。

有几种不同的方法可以做到这一点,但我建议不要在控制器级别授予对顾问的访问权限,因为您要将特权帐户(超级管理员和管理员)与受限制的帐户(顾问)混合。

我会创建一个可由所有三个角色访问的新控制器,并在此处移动此操作。然后,您可以将特权方法保留在原始控制器中。

[CustomAuthorise(SuperAdministrator, Administrator)]
public class PrivilegedController : Controller
{

    // Should only accessible by SuperAdministrators and Administrators
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }

}

[CustomAuthorise(SuperAdministrator, Administrator, Consultant)]
public class LessPrivilegedController : Controller
{

    [HttpGet]
    public ActionResult SomeAction()
    {
        return View();
    }
}