[英]Dynamically add roles to authorize attribute for controller
我需要啟用我的管理員用戶即時更改用戶的訪問權限,以便他們可以創建新角色並為這些角色添加權限。
我希望能夠創建一個Authorize
屬性來粘貼在我可以從數據庫添加角色的控制器類之上,這樣我就不必在開發過程中“設置”角色,如[Authorize(Roles="Role1, Role2")]
等
所以像[Authorize(Roles = GetListOfRoles()]
我發現了這個問題 - ASP.NET MVC授權用戶有很多角色 ,它做了類似的事情,但也許有一種方法可以改變它,以便它從數據庫中獲取權限/角色列表?
這就是我如何根據該用戶角色的權限提取可以為每個方法授權用戶的屬性。 我希望這有助於其他人:
/// <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;
}
}
這樣的事情怎么樣:
[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中維護一個授權角色列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.