2015-10-03 53 views
1

我有一個CustomAuthorizeAttribute類以這種方式實現。使用自定義授權時,響應始終爲200確定

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)和預期不會進入服務端點。問題是我的HTTPResponse=200 OK當我調用API而不是403 UnAuthorized。我的代碼有什麼問題?

更新:

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

,您在繼承哪個類和命名空間的'CustomAuthorizeAttribute'? –

+0

@DavidTansey,更新了問題。 – naveen

回答

1

看起來你收到的客戶端,因爲響應轉換成一個302重定向到登錄頁面(這是你可能會想要什麼如果請求的200響應來自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")}) 

這也將要求您在Startup.Auth.vbConfigureAuth功能塊之後和End Class語句之前底部添加的功能IsApiRequest

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/

+0

謝謝。這是一個非常有價值的片段。 – naveen

+1

不客氣 - #SOreadytohelp ...如果我的答案解決了您的問題,請考慮將答案標記爲已接受。 –