ASP.NET 身份动态角色授权

ASP.NET Identity Dynamic Role Authorization

由于我是 ASP.NET Identity 的新手,我正在观看有关 MVA 的视频时,Jeremy Foster 在演示时问了一个问题,即如何使以下内容动态化:

[Authorize("Administrators, Users")]
public ActionResult SomeAction()
{
  //Access to only admins and users
}

作为回答,Adam Tuliper 说可以使用 Claims 以某种方式完成,但我在 Internet 上找不到任何具体内容,或者我可能不理解。但如果有人能告诉我如何做到这一点,我将不胜感激。

这很重要,因为稍后,我可能希望允许 SomeAction 被另一个角色访问,如果我每次都需要为此重新编译和部署我的应用程序,那不是很好。此外,我可能会将控制权授予用户以更改其他类型用户的访问权限。

过去,我通过覆盖 Authorize 属性来完成此操作,我从 cookie 中提取用户的 RoleId,并从数据库中检查用户是否有权访问所请求的操作。但不确定如何使用声明来完成。

像这样的事情怎么样: 您可以将它与数据库一起使用,或者只是在 web.config.

中维护授权角色列表
 [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class MyCustomAuthorizationAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            // Do some logic here to pull authorised roles from backing store (AppSettings, MSSQL, MySQL, MongoDB etc)
            ...
            // Check that the user belongs to one or more of these roles 
            bool isUserAuthorized = ....;

            if(isUserAuthorized) 
                return true;

            return base.AuthorizeCore(httpContext);
        }
    }