如何使用 OWIN Security 将自定义身份验证属性添加到 Web API?

How can I add a custom authentication attribute to Web API using OWIN Security?

通常我会要求像这样对控制器进行身份验证:

Namespace Controllers
    <Authorize(Users:="user1")>
    Public Class Module1Controller
        Inherits ApiController

        ' GET: api/Module1
        Public Function GetValues() As IEnumerable(Of String)

            Return New String() {"This", "is", "Module1", System.Web.HttpContext.Current.User.Identity.Name}
        End Function

但除此之外,我们希望使用相同的方法进行身份验证,除了从本地数据库 table(在 SSMS 中)中提取用户列表以及他们有权访问和检查的控制器针对他们查看他们是否有权访问特定控制器(本例中为 Module1)。所以我遵循了几个关于创建自定义身份验证属性的示例,但我无法让它工作。这个想法是实现这个 class:

Public Class CustomAuthorize
    Inherits AuthorizeAttribute
    Protected Function AuthorizeCore(ByVal httpContext As HttpContextBase) As Boolean
        Dim users As String() = {"user1", "user2"}
        If users.Contains(httpContext.User.Identity.Name) Then Return True
        Return False
    End Function
End Class

实际上,字符串数组会从数据库查询中填充,然后在控制器顶部使用 <CustomAuthorize> 而不是 <Authorize(Users:="user1">... 但是当我 运行 它,它永远不会进入 CustomAuthorize class。感谢任何帮助。

这就是最终的效果:

Public Class CustomAuthorize
    Inherits System.Web.Http.AuthorizeAttribute
    Protected Overrides Function IsAuthorized(ByVal actionContext As System.Web.Http.Controllers.HttpActionContext) As Boolean
        Dim users As String() = {"user1", "user2"}
        If users.Contains(httpContext.User.Identity.Name) Then Return True
        Return False
    End Function
End Class