2014-01-25 24 views
0

我在單個頁面應用程序中使用Breeze保存到asp.net web api服務器。我的應用程序使用表單身份驗證,我的Breeze控制器使用Authorize屬性進行裝飾;如何確保Breeze.js保存不會觸發瀏覽器的驗證對話?

[System.Web.Http.Authorize] 
[BreezeController] 
public class ReminderController : ApiController 
{ ... } 

我所看到的,一旦其中的微風試圖保存的問題,並請求完成之前,瀏覽器立即彈出一個用戶名/密碼認證對話框。我不完全確定爲什麼會發生這種情況,因爲aspx cookie未設置爲過期,但我可以通過登錄到我的應用程序來複制它,刪除cookie並觸發Breeze保存。如果我點擊對話框上的取消,我的服務器會響應我的客戶端代碼處理的401。我想確保auth對話從不向用戶顯示。這種情況發生在Chrome和IE中,但我確定它在舊版Chrome穩定版中沒有這樣做。

請求可以在這裏看到,仍被列爲待定,而顯示的對話框

Request

感謝

回答

1

下面是我用來解決這個問題的自定義的Authorize屬性(警告,從VB.NET自動轉換爲C#,所以它可能不是100%正確的!)。如果用戶已經通過身份驗證,它將發送403狀態而不是401,以阻止瀏覽器提示用戶登錄。在IE和Firefox中測試。

/// <summary> 
/// Custom <see cref="AuthorizeAttribute"/> for WebAPI that sends a 403 Forbidden status instead 
/// of 401 Unauthorized, if the user is authenticated, so that the browser will not display a 
/// logon prompt. 
/// </summary> 
/// <remarks></remarks> 
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] 
public class MyAuthorizeAttribute : System.Web.Http.AuthorizeAttribute 
{ 
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) 
    { 
     var user = Thread.CurrentPrincipal; 
     if (user != null && user.Identity.IsAuthenticated) { 
      // If the user is authenticated then we don't want to prompt them to authenticate. 
      // Ajax requests get a forbidden status code to stop the browser login prompt, 
      // since Unauthorized (401) would cause the browser to display a login dialog. 
      actionContext.Response = actionContext.ControllerContext.Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Forbidden"); 
     } else { 
      // If the user isn't authenticated then do the normal thing 
      base.HandleUnauthorizedRequest(actionContext); 
     } 
    } 
} 
+0

我已將此作爲答案,因爲我似乎無法找到一個方法來移除401響應的'WWW-Authenticate'頭(也許是IIS加入他們嗎?)一403是看似只有這樣解決這個問題。 – SeeNoWeevil

0

似乎沒有可靠的,跨瀏覽器的方式,以防止在對話客戶端。檢查Fiddler我可以看到cookie到期時對ajax請求的實際響應(令人討厭的Chrome開發工具無法顯示此內容,只是處於「待定」狀態)包含WWW-Authenticate標頭。奇怪的是,本地運行的IIS Express 沒有包含這些頭文件,並且對話框從不顯示。只有當我在我的提供商上發佈到完整的IIS時纔會顯而易見。計劃是覆蓋Web Api Authorize屬性(處理授權失敗的方法)並刪除WWW-Authenticate標頭。

我不知道爲什麼IIS 8.0/Express返回不同的頭文件。

相關問題