c# - 自定义 AuthorizeAttribute 未实现
问题描述
在我们的 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
,一切都按预期工作。
推荐阅读
- javascript - 如何根据从 JSON 接收的数据生成动态表单
- javascript - 如何选择 eval() 值
- angular - 反应式表单组验证 - 两级验证(个人和组级别)
- javascript - 如何修复 React Developper Tools 在默认 React 页面上给出的错误消息?
- c# - 为什么我会收到“错误 CS1056:意外字符 '$'”在此处放置 $ 标记?我的编译器有问题?
- python - Pandas 按多列分组并按行获取输出
- mongodb - 取消选择 Mongoose 模型中的 ref 字段
- c# - 将按钮绑定到 UWP 中 ViewModel 中的命令
- if-statement - 我需要“if and”语句的正确语法
- python - 错误:在 Python3 中不可能进行类建议 topia.termextract