所以我认为你说的是:只有当用户有 perm1、perm2 时才可以访问 ActionA,类似地,当用户有 perm1 和 perm3 时可以访问 ActionB
我给出的代码是为了说明,我没有编译它。但是会给你我所说的方法的图片
第 1 步:您可以继续创建一个带有标志属性的权限枚举
第 2 步:根据存储在数据存储中的用户权限向当前委托人添加声明。
第 3 步:当调用 Action 时,授权访问索赔
[Flags]
enum PermType
{
None = 0x0,
Perm1 = 0x1,
perm2 = 0x2,
perm3 = 0x4,
perm4 = 0x8,
perm5 = 0x10
}
向 CurrentPrincipal 添加声明
var currentPrincipal = ClaimsPrincipal.Current;
var cms = currentPrincipal.Claims;
var permissions = PermType.Perm1 | PermType.perm2;
var claims = cms.ToList();
claims.Add(new Claim("Action1", permissions.ToString()));
claims.Add(new Claim("Action2", permissions.ToString()));
claims.Add(new Claim("Action3", permissions.ToString()));
System.Threading.Thread.CurrentPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims));
检查用户是否可以访问特定操作
public bool CanAccessThisAction(string acionName,PermType requiredPerms)
{
var claim = principal.Claims.FirstOrDefault(c => c.Type == acionName);
if (customPermissionClaim != null)
{
//check if required permission is present in claims for this user
//return true/false
}
return false;
}
行动上
public ActionResult TestAction(string id)
{
if(CanAccessThisAction("TestAction",PermType.Perm1|PermType.perm3|PermType.perm5))
{
//do your work here
}
else
{
//redirect user to some other page which says user is not authorized
}
}