使用自定义授权时,响应始终为200

时间:2015-10-03 19:51:35

标签: asp.net asp.net-web-api2

我有一个CustomAuthorizeAttribute类这样实现。

Public Overrides Sub OnAuthorization(actionContext As HttpActionContext)
    If Authorize(actionContext) Then
        Return
    End If
    HandleUnauthorizedRequest(actionContext)
End Sub

Protected Overrides Sub HandleUnauthorizedRequest(actionContext As HttpActionContext)
    Dim challengeMessage = New HttpResponseMessage(HttpStatusCode.Unauthorized)
    challengeMessage.Headers.Add("WWW-Authenticate", "Basic")
    Throw New HttpResponseException(challengeMessage)

End Sub

Private Function Authorize(actionContext As HttpActionContext) As Boolean
    Dim isAuthorized = False
    Try
        'make it true if all goes validations go well
        Return True
    Catch generatedExceptionName As Exception
    End Try
    Return isAuthorized
End Function

授权失败时,它会在Throw New HttpResponseException(challengeMessage)上被点击,并且永远不会按预期进入服务端点。当我调用API而不是HTTPResponse=200 OK时,问题是我的403 UnAuthorized。我的代码出了什么问题?

更新

<AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method, AllowMultiple:=False, Inherited:=True)>
Public Class CustomAuthorizeAttribute
    Inherits AuthorizeAttribute

1 个答案:

答案 0 :(得分:1)

看起来您在客户端收到的200响应是因为响应被转换为302重定向到登录页面(如果请求来自ASP.NET WebForm或MVC视图,这可能是您想要的)。

尝试修改Startup.Auth.vb并将原始app.UseCookieAuthentication替换为以下内容:

    app.UseCookieAuthentication(New CookieAuthenticationOptions() With {
        .AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        .Provider = New CookieAuthenticationProvider() With {
            .OnValidateIdentity = SecurityStampValidator.OnValidateIdentity(Of ApplicationUserManager, ApplicationUser)(
                validateInterval:=TimeSpan.FromMinutes(30),
                regenerateIdentity:=Function(manager, user) user.GenerateUserIdentityAsync(manager)),
            .OnApplyRedirect =
                Function(ctx)
                    If Not IsApiRequest(ctx.Request) Then
                        ctx.Response.Redirect(ctx.RedirectUri)
                    End If
                End Function
        },
        .LoginPath = New PathString("/Account/Login")})

还要求您在IsApiRequest功能块之后和Startup.Auth.vb语句之前的ConfigureAuth底部添加以下函数End Class

Private Shared Function IsApiRequest(request As IOwinRequest) As Boolean
    Dim apiPath As String = VirtualPathUtility.ToAbsolute("~/api/")
    Return request.Uri.LocalPath.StartsWith(apiPath)
End Function

这将避免重定向到登录表单(对于指向WebApi路由的请求),并返回代码正在抛出的HTTP状态401。

有关此内容的更多信息(仅限C#)可在本文中找到:

http://brockallen.com/2013/10/27/using-cookie-authentication-middleware-with-web-api-and-401-response-codes/