我有一个需要根据“权利”授权的应用程序
权利非常大(大约200,也许还会更多)
可以将一个或多个权限分配给一个端点
示例:
[HasRights(Rights.AddPayer, Rights.DeletePayer)]
[HttpPost]
public IActionResult AddPayer([FromBody]PayerModel model)
{
}
我开始为该属性建立一个类
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false)]
public class HasRightsAttribute : AuthorizeAttribute, IAuthorizationFilter
{
HashSet<Rights> userRights;
public HasRightsAttribute(params Rights[] rights)
{
userRights = rights.ToHashSet();
}
public void OnAuthorization(AuthorizationFilterContext context)
{
Claim claim = context.HttpContext.User.Claims.FirstOrDefault();
int userId = int.Parse(claim.Value);
List<int> rights;
using (var myContext = new myDB())
{
rights = (from UR in myContext.TblUserRole
join RR in myContext.TblRoleRight on UR.RoleID equals RR.RoleID
where UR.UserID == userId
select RR.RightID)
.ToList();
}
var permission = rights.Any(x => userRights.Contains((Rights)Enum.ToObject(typeof(Rights), x)));
if (!permission)
{
//context.Result = new ForbidResult();
Debug.WriteLine("NO ACCESS");
}
else
{
Debug.WriteLine("YOU HAVE ACCESS");
}
}
}
该属性有效。这是个好方向吗?
我想创建最简单的授权方式