0

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();
        }
    }
}
Peter Kellner
  • 14,748
  • 25
  • 102
  • 188
  • This [blog](http://bitoftech.net/2015/03/31/asp-net-web-api-claims-authorization-with-asp-net-identity-2-1/) by @taiseer talks about a `ClaimsAuthorizationAttribute` he wrote on ASP.Net Identity 2.1 and Web API. It allows you to specify the claim type and value, with the attribute. I have not tried it, and I'm not sure if it will work on MVC 5. You might want to give it a try. [Or you can check and try the answers to this [SO question](https://stackoverflow.com/questions/19363809/mvc5-claims-version-of-the-authorize-attribute) – Frank Fajardo Aug 04 '17 at 01:04
  • I'm not so much interested in finding someone else who has written, I'm trying to find out if Microsoft did and I'm just not finding it. – Peter Kellner Aug 04 '17 at 01:11
  • It does not look like there is unless you want to move to .NET Core: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/claims – Frank Fajardo Aug 04 '17 at 01:13
  • ClaimsPrincipalPermission in conjunction with inheriting from ClaimsAuthorizationManager – Fran Aug 04 '17 at 02:26
  • @PeterKellner No, there is nothing like that provided by MS for MVC5. So your own implementation will have to be used. – trailmax Aug 04 '17 at 10:05

0 Answers0