我正在使用使用Identity 2的ASP.NET MVC5。我想限制对具有特定声明的用户的控制器访问。我已经创建了自己的自定义属性,如下所示,并将其分配给MVC Controller操作。
有这样的内置功能吗?也就是说,我是否已经可以使用自定义属性而不是编写自己的属性?
[ManagerByClaimAttribute]
public ActionResult CheckLoggedInUserIsManagerByClaimWithAttribute()
{
// will not get here unless manager claim attribute set
// becasue of custom attribute [ManagerByClaimAttribute]
return View("CheckLoggedInUserIsManagerByClaimWithAttribute");
}
...
public class ManagerByClaimAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
var principal = (ClaimsPrincipal) Thread.CurrentPrincipal;
Claim claims = principal.Claims
.FirstOrDefault(c => c.Type == "RoleAssigned" &&
c.Value == "managerbyclaim");
if (claims == null)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
}