繁体   English   中英

未实现自定义 AuthorizeAttribute

[英]Custom AuthorizeAttribute not being implemented

在我们的 MVC 解决方案中,我们有两个AuthorizeAttribute自定义实现 - 一个名为BasicHttpAuthorizeAttribute并且已在生产中使用多年,另一个RoleAuthorizeAttribute是最近添加的。

创建RoleAuthorizeAttribute我只是简单地复制了BasicHttpAuthorizeAttribute并修改了一些已经覆盖的方法。

这两个属性都用于对用户进行身份验证,而RoleAuthorizeAttribute用于验证用户是否具有所需的角色。

但是, RoleAuthorizeAttribute永远不会对用户进行身份验证。 它只是没有被调用,而是当未登录的用户到达控制器操作并且代码请求上下文用户时,我们的 MVC 控制器抛出异常。

以下是此自定义AuthorizeAttribute的大纲。 如果我在所有这些方法上放置断点,我会发现在发出请求时它们都没有被命中。

谁能解释为什么不使用此类来验证用户? 为什么未经身份验证的用户没有被重定向到登录页面,但是如果我将RoleAuthorize交换为BasicHttpAuthorize或只是基本Authorize那么它们会重定向?

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]    
public class RoleAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
    /// <summary>
    /// Gets or sets the <see cref="Role"/> enumerations required for authorization.
    /// </summary>
    public Role[] RequiredRoles
    {
        get {...}
        set {...}
    }

    public bool RequireSsl { get; set; };

    public bool RequireAuthentication { get; set; }

    public RoleAuthorizeAttribute(params Role[] requiredRoles)
    {
        // ...
    }

    public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        // ...
    }

    protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        // ...
    }

    private bool Authenticate(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        // ...
    }

    public static bool TryGetPrincipal(string authHeader, out IPrincipal principal)
    {
        // ...
    }

    public static bool TryGetAuthCookie(out IPrincipal principal)
    {
        // ...
    }

    private static string[] ParseAuthHeader(string authHeader)
    {
        // ...
    }

    private static bool TryGetPrincipal(string username, string password, out IPrincipal principal)
    {
        // ...
    }
}

这是其用法的示例:

namespace MyProject.Areas.Customer.Controllers
{
    [RoleAuthorize(Role.Customer, Role.CompanyAdmin)]
    public partial class OrderController : MyCustomController
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof (OrderController));

        public ActionResult Index(int id)
        {
            // ...
        }
    }
}

我们使用基本身份验证,因此有一个标头集:

在此处输入图片说明

我见过询问相同问题的旧问题,但在这些情况下,它们还覆盖了AuthorizeCore方法,该方法似乎不再存在于AuthorizeAttribute类中。

我自己弄清楚为什么会发生这种情况。

有两个AuthorizeAttributes - 一个在System.Web.Http命名空间中,另一个在System.Web.Mvc 我没有意识到这一点,并试图建立一个尺寸适合所有的属性,所以我的属性工作的WebAPI请求,但不是MVC控制器的请求。

这两个属性的区别在于OnAuthorize方法中,它们每个都采用不同的上下文参数。

一旦我构建了两个独立的属性(几乎相同),每个属性都源自不同的AuthorizeAttribute ,一切都按预期工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM