I'm using ASP.NET MVC5 which uses Identity 2. I want to restrict controller access to users that have a specific claim. I've created my own custom attribute as shown below as well as assigned it to an MVC Controller action.
Is there any built in capability like this? That is, is there a custom attribute already someplace I can use for this rather than writing my own?
[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();
}
}
}