自定义AuthorizeAttribute未实现

问题描述 投票:1回答:1

在我们的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)
        {
            // ...
        }
    }
}

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

enter image description here

我见过older questions asking about the same problem,但在那些情况下,它们也覆盖了AuthorizeCore类似乎不再存在的AuthorizeAttribute方法。

c# authentication authorization authorize-attribute asp.net-authorization
1个回答
4
投票

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

有两个AuthorizeAttributes - 一个在System.Web.Http命名空间,另一个在System.Web.Mvc。我没有意识到这一点,并且正在尝试构建一个适合所有人的属性,因此我的属性适用于WebAPI请求,但不适用于MVC控制器请求。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.