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

时间:2015-05-07 11:19:46

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

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

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

类似于[Authorize(Roles = GetListOfRoles()]

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

2 个答案:

答案 0 :(得分:16)

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

/// <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;
    }
}

答案 1 :(得分:8)

这样的事情:

[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);
    }
}

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