簡體   English   中英

如何自動使無憑據的Web請求失敗,而不提示輸入用戶名/密碼?

[英]How do I auto-fail uncredentialed Web Request rather than prompting for username/password?

我有一個本地api,它出於身份驗證目的向外部api發出了輔助請求。 在本地api執行其工作之前,它將通過WebRequest將請求標頭(應包括XHR身份驗證標頭)轉發到身份驗證api。 如果請求沒有失敗(未授權401),則本地api會執行其工作。 如果第二個請求確實拋出,那么我將返回未授權狀態。 一切正常---除了當我通過本地api發出非憑據請求時,瀏覽器會以本機Windows用戶名/密碼登錄彈出窗口提示我。 如果我直接針對輔助api而不是通過本地api發出相同的非憑據請求,則該請求只會失敗,並且永遠不會收到提示。 我希望我的本地api表現出相同的行為:

  • 憑證或非憑證請求進入。
  • 將請求標頭傳遞到輔助api進行身份驗證。
  • 請求返回200(憑證良好)或401(憑證不良或丟失)。

我嘗試過使用request.PreAuthenticaterequest.Credentials ,但是我嘗試過的值似乎都無法阻止彈出窗口的顯示。

// Create the authorization request object
string authUrl = @"https://auth-service-url.com/api/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(authUrl);

// Relay any params from this request onto the outgoing authorization request
CopyHttpParameters(request);

// Retrieve the response
try {
    WebResponse response = request.GetResponse();
    // If GetResponse doesn't throw, then the user is authorized
    return Request.CreateResponse(HttpStatusCode.OK);
}
catch(Exception)
{
    // If GetResponse throws, then the user is unauthorized
    return Request.CreateResponse(HttpStatusCode.Unauthorized);
}

上面的CopyHttpParameters方法(基於此答案 )不包括在內,但可以使用。 具有嵌入式XHR憑據的傳入請求按預期成功。 問題是非憑據請求,因此出於我們的目的,可以完全刪除CopyHttpParameters函數調用。 我想要的是以下try塊完全失敗,而沒有提示用戶登錄。 當我直接從瀏覽器中單擊它時,這就是上面的authUrl服務的行為。 進行非憑據的WebRequest調用時如何獲得此行為?

問題似乎在這里:

return Request.CreateResponse(HttpStatusCode.Unauthorized);

這與我的applicationhost.config中的windowsAuthentication結合在一起似乎正在觸發彈出窗口。

將以下內容添加到我的Web.config中似乎抑制了彈出窗口:

<location path="api">
    <system.webServer>
        <security>
            <authentication>
                <windowsAuthentication enabled="false" />
            </authentication>
        </security>
    </system.webServer>
</location>

location塊可能不是必需的,但我不想覆蓋站點范圍的默認值,以防萬一。 這樣可以確保僅針對我的api路由關閉Windows身份驗證。

現在,當我返回Unauthorized ,請求僅按預期失敗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM