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

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

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

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

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

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

 ///  /// Custom authorization attribute for setting per-method accessibility ///  [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class SetPermissionsAttribute : AuthorizeAttribute { ///  /// The name of each action that must be permissible for this method, separated by a comma. ///  public string Permissions { get; set; } protected override bool AuthorizeCore(HttpContextBase httpContext) { SalesDBContext db = new SalesDBContext(); UserManager userManager = new UserManager(new UserStore(new ApplicationDbContext())); ApplicationDbContext dbu = new ApplicationDbContext(); bool isUserAuthorized = base.AuthorizeCore(httpContext); string[] permissions = Permissions.Split(',').ToArray(); IEnumerable perms = permissions.Intersect(db.Permissions.Select(p => p.ActionName)); List roles = new List(); 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; } } 

这样的事情怎么样:

 [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中维护一组授权角色。