自定义授权在操作级别上有效,但在控制器级别上无效

本文关键字:控制器 无效 有效 自定义 授权 操作 | 更新日期: 2023-09-27 18:28:43

正如我所知,在默认情况下,用authorize属性装饰的控制器内的所有操作都将采用相同的属性值(例如,如果控制器authorize attribute roles=admin,则所有没有用任何属性装饰的操作都将自动采用相同的role=admin),但在我的情况下,这种逻辑不起作用

这是我的自定义授权详细信息

 public class CustomAuthorize : AuthorizeAttribute
    {
        public string Url { get; set; }
        public string Claims { get; set; }
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (!httpContext.User.Identity.IsAuthenticated)
            {
                return false;
            }
            else if (!string.IsNullOrWhiteSpace(Claims))
            {
                var claims = httpContext.GetOwinContext().Authentication.User.HasClaim(t => t.Type == "claim"
                && Claims.Split(',').Contains(t.Value));
                if (!claims)
                {
                    return false;
                }
                else
                    return true;
            }
            else if (!string.IsNullOrWhiteSpace(Roles))
            {
                var roles = httpContext.GetOwinContext().Authentication.User.HasClaim(t => t.Type == "role"
                && Roles.Split(',').Contains(t.Value));
                if (!roles)
                {
                    return false;
                }
                else
                    return true;
            }
            return base.AuthorizeCore(httpContext);
        }
        public bool IsAuthorized(string claim)
        {
            if (!string.IsNullOrEmpty(Claims))
                return Claims.Split(',').Contains(claim);
            return true;
        }
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (!string.IsNullOrEmpty(Url))
                filterContext.Result = new RedirectResult(Url);
            else
                base.HandleUnauthorizedRequest(filterContext);
        }
    }

一种检查身份验证的辅助方法

 public static bool ActionIsAuthorized(this HtmlHelper helper, string actionName, string controllerName)
        {
            IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
            ControllerBase controller = factory.CreateController(helper.ViewContext.RequestContext, controllerName) as ControllerBase;
            var controllerContext = new ControllerContext(helper.ViewContext.RequestContext, controller);
            var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
            var actionDescriptor = controllerDescriptor.FindAction(controllerContext, actionName);
            AuthorizationContext authContext = new AuthorizationContext(controllerContext, actionDescriptor);
            foreach (var authAttribute in actionDescriptor
                .GetFilterAttributes(true)
                .Where(a => a is CustomAuthorize).Select(a => a as CustomAuthorize))
            {
                authAttribute.OnAuthorization(authContext);
                if (authContext.Result != null)
                    return false;
            }
            return true;
        }

以及在视图中的使用

@if(Html.ActionIsAuthorized("Index","Appointment", new {area="Employee"})){
    @Html.ActionLink("Appointments","Index","Appointment",new {area = "Employee"})
}

当我使用上面的代码如下,它将不起作用(预约链接仍然显示)

[CustomAuthorize(Claims="Add Appointment",Url="~/Employee/Home/Login")]
public class AppointmentController: BaseController
{
      public ActionResult Index()
      {
          // code here
      }
}

而如果我以以下方式使用它,它可以

public class AppointmentController: BaseController
{
      [CustomAuthorize(Claims="Add Appointment",Url="~/Employee/Home/Login")]
      public ActionResult Index()
      {
          // code here
      }
}

有人能告诉我,当我用装饰控制器时,为什么动作默认不带属性吗?或者我错过了什么?

自定义授权在操作级别上有效,但在控制器级别上无效

看起来问题出在您的自定义ActionIsAuthorized html帮助程序中。您只在操作描述符上查找属性,而不在控制器描述符上查找。因此,请确保您也查看controllerDescriptor.GetCustomAttributes():

var actionAttributes = actionDescriptor.GetCustomAttributes(typeof(CustomAuthorize), true);
var controllerAttributes = controllerDescriptor.GetCustomAttributes(typeof(CustomAuthorize), true);
var attributes = actionAttributes.Concat(controllerAttributes).OfType<CustomAuthorize>().ToList();
foreach (var authAttribute in attributes)
{
    ...
}