从方法AuthorizeCore

时间:2016-05-18 16:45:14

标签: asp.net-mvc-5 asp.net-identity claims-based-identity

我正在尝试使用声明授权,而我正在使用此数据注释

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

当我尝试访问 test 方法时,我将重定向到 AuthorizeCore 方法:

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;
 }

当我的用户能够访问 test 方法时,这些工作正常,但是当用户无法进行时,没有任何反应。

我的问题是:如何在返回false时返回方法? 感谢

1 个答案:

答案 0 :(得分:1)

感谢@trailmax,我可以解决我的问题:

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"}
            });
        }
    }
}

非常感谢