Search code examples
asp.net-mvc-5asp.net-identityclaims-based-identity

Get return from method AuthorizeCore


I'm trying to use claims authorization and i'm using this data-annotation

[ClaimsAuthorize(ClaimTypes.Role, "Admin")]
public void Test()
{
  ....
}

When i try to access test method i'm redirect to AuthorizeCore method:

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
      var identity = (ClaimsIdentity)httpContext.User.Identity;
      var claim = identity.Claims.FirstOrDefault(c => c.Type == ClaimType);
      if(claim != null)
      {
          return claim.Value == ClaimValue;
      }
          return false;
 }

When my user is able to access test method these work fine but when user is not able to it nothing happens.

My question is: How can i get method return when it returns false? Thanks


Solution

  • Thanks to @trailmax i can solve my problem:

    public class ClaimsAuthorizeAttribute : AuthorizeAttribute
    {
        public string ClaimType { get; set; }
        public string ClaimValue { get; set; }
    
        public ClaimsAuthorizeAttribute(string claimType, string claimValue)
        {
            ClaimType = claimType;
            ClaimValue = claimValue;
        }
    
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var user = (ClaimsIdentity)HttpContext.Current.User.Identity;
            var claim = user.Claims.FirstOrDefault(c => c.Type == ClaimType);
    
            if (claim != null && claim.Value == ClaimValue)
            {
                base.OnAuthorization(filterContext);
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(){
                    {"controller", "Contas"},
                    {"action", "NaoAutorizado"}
                });
            }
        }
    }
    

    Thanks a lot