动态添加角色以授权控制器的属性

bar*_*e.m 22 c# asp.net asp.net-mvc authorize-attribute asp.net-identity

我需要启用我的管理员用户即时更改用户的访问权限,以便他们可以创建新角色并为这些角色添加权限.

我希望能够创建一个Authorize属性,以便在我的控制器类之上,我可以从数据库添加角色,这样我就不必在开发过程中"设置"角色,如[Authorize(Roles="Role1, Role2")]等.

所以像 [Authorize(Roles = GetListOfRoles()]

我发现了这个问题 - ASP.NET MVC授权用户有很多角色,它做了类似的事情,但也许有一种方法可以改变它,以便从数据库中获取权限/角色列表?

bar*_*e.m 18

这就是我如何根据该用户角色的权限提取可以为每个方法授权用户的属性.我希望这有助于其他人:

/// <summary>
/// Custom authorization attribute for setting per-method accessibility 
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class SetPermissionsAttribute : AuthorizeAttribute
{
    /// <summary>
    /// The name of each action that must be permissible for this method, separated by a comma.
    /// </summary>
    public string Permissions { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        SalesDBContext db = new SalesDBContext();
        UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
        ApplicationDbContext dbu = new ApplicationDbContext();

        bool isUserAuthorized = base.AuthorizeCore(httpContext);

        string[] permissions = Permissions.Split(',').ToArray();

        IEnumerable<string> perms = permissions.Intersect(db.Permissions.Select(p => p.ActionName));
        List<IdentityRole> roles = new List<IdentityRole>();

        if (perms.Count() > 0)
        {
            foreach (var item in perms)
            {
                var currentUserId = httpContext.User.Identity.GetUserId();
                var relatedPermisssionRole = dbu.Roles.Find(db.Permissions.Single(p => p.ActionName == item).RoleId).Name;
                if (userManager.IsInRole(currentUserId, relatedPermisssionRole))
                {
                    return true;
                }
            }
        }
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*ker 10

这样的事情怎么样:

[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);
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以将它与数据库一起使用,或者只是在web.config中维护一个授权角色列表.

  • 我想我知道你要去哪里,但是为了能够从这个q/a获得知识的其他人,你能编辑你的答案以使其更全面(比如包括授权用户的逻辑,也许包括来自db的IdentityRoles列表作为示例),然后我将其标记为已接受. (5认同)