首页 > 解决方案 > 自定义 AuthorizeAttribute 未实现

问题描述

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

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

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

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

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

谁能解释为什么这个类没有被用来验证用户?为什么未经身份验证的用户没有被重定向到登录页面,但是如果我交换RoleAuthorizeBasicHttpAuthorize只是交换基础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类中的方法。

标签: c#authenticationauthorizationauthorize-attributeasp.net-authorization

解决方案


我自己弄清楚为什么会这样。

有两个AuthorizeAttributes- 一个在System.Web.Http命名空间中,另一个在System.Web.Mvc. 我没有意识到这一点,并试图构建一个万能的属性,所以我的属性适用WebAPI 请求,但不适用于 MVC 控制器请求。

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

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


推荐阅读