我有一个授权要求,我的安全角色基于操作方法,使用默认的 asp.net mvc 授权无法实现。所以我创建了以下操作过滤器,以实现我的自定义授权要求:-
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class CheckUserPermissionsAttribute : ActionFilterAttribute
{
Repository repository = new Repository();
public string Model { get; set; }
public string Action { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// var user = User.Identity.Name; // or get from DB
string ADusername = filterContext.HttpContext.User.Identity.Name.Substring(filterContext.HttpContext.User.Identity.Name.IndexOf("\\") + 1);
if (!repository.can(ADusername,Model,Action)) // implement this method based on your tables and logic
{
filterContext.Result = new HttpUnauthorizedResult("You cannot access this page");
}
base.OnActionExecuting(filterContext);
}
}
它正在调用以下存储库方法:-
public bool can(string user, string Model, string Action)
{
bool result;
bool result2;
int size = tms.PermisionLevels.Where(a5 => a5.Name == Action).SingleOrDefault().PermisionSize;
var securityrole = tms.SecurityroleTypePermisions.Where(a => a.PermisionLevel.PermisionSize >= size && a.TechnologyType.Name == Model).Select(a => a.SecurityRole).Include(w=>w.Groups).Include(w2=>w2.SecurityRoleUsers).ToList();//.Any(a=> a.SecurityRoleUsers.Where(a2=>a2.UserName.ToLower() == user.ToLower()));
foreach (var item in securityrole)
{
result = item.SecurityRoleUsers.Any(a => a.UserName.ToLower() == user.ToLower());
var no = item.Groups.Select(a=>a.TMSUserGroups.Where(a2=>a2.UserName.ToLower() == user.ToLower()));
result2 = no.Count() == 1;
if (result || result2)
{
return true;
}}
return false;
我在我的控制器类中调用动作过滤器如下:-
[CheckUserPermissions(Action = "Read", Model = "Server")]
但我有以下担忧:-
在我的存储库中,我将检索所有用户和组(调用 .Tolist() 时),然后检查当前登录用户是否在这些值内。在处理大量用户时,哪个不是很可扩展?
每次用户调用操作方法时,都会运行相同的安全代码(当然,理想情况下,用户权限可能会在用户会话期间发生变化),,这可能会导致性能问题?
那么,考虑到这两个问题,谁能告诉我如何改进我目前的实施?谢谢