WebView2 應用程式的基本驗證

基本驗證 是屬於 HTTP 通訊協定一部分的 驗證 方法。

Basic authentication for WebView2 apps includes a sequence of authentication and navigation steps to retrieve a webpage from an HTTP server. The WebView2 control acts as an intermediary for communication between the host app and the HTTP server.

使用 HTTPS 傳送認證

警告:使用基本驗證時,您必須使用 HTTPS。 否則不會加密使用者名稱和密碼。 您可能想要考慮其他形式的驗證。

基本驗證的 HTTP 標準包含未加密 (使用者名稱和密碼) 驗證認證。 因此,您必須使用 https ,以確保認證已加密。

導覽事件的順序

基本驗證事件會在事件序列的中間發生:

  1. NavigationStarting - 導覽事件
  2. ContentLoading - navigation event
  3. BasicAuthenticationRequested
  4. DOMContentLoaded
  5. NavigationCompleted - navigation event

如需詳細資訊,請參閱 WebView2 應用程式的導覽事件

HTTP 伺服器、WebView2 控制項和主應用程式之間的通訊

  • HTTP 伺服器會檢查驗證 (使用者名稱和密碼認證) ,並傳回錯誤檔或要求的網頁。

  • WebView2 控制項實例會引發事件。 WebView2 控制項位於 HTTP 伺服器和主應用程式之間。 WebView2 控制項可作為主應用程式與 HTTP 伺服器之間通訊的媒介。

  • 您會撰寫 主應用程式。 主應用程式會在事件的引數上設定使用者名稱和密碼, () EventArgs 回應物件。

BasicAuthenticationRequestedEventArgsResponse具有 屬性。 屬性 Response 是包含使用者名稱和密碼屬性的物件。

巡覽事件的順序

下圖顯示 WebView2 應用程式基本驗證的流覽事件流程:

WebView2 應用程式基本驗證的流覽事件流程

  1. 主應用程式會告知 WebView2 控制項流覽至 URI。

  2. WebView2 控制項會與 HTTP 伺服器交談,要求在指定的 URI 取得檔。

  3. HTTP 伺服器會回復 WebView2 控制項,指出「您無法取得該 URI (檔) 沒有驗證」。

  4. WebView2 控制項會告訴主應用程式「需要驗證」 (這是 BasicAuthenticationRequested 事件) 。

  5. 主應用程式會藉由提供使用者名稱和密碼給 WebView2 控制項來回應該事件。

  6. WebView2 控制項會再次向 HTTP 伺服器要求 URI,但這次使用驗證 (使用者名稱和密碼) 。

  7. HTTP 伺服器會評估使用者名稱和密碼) (認證。

  8. HTTP 伺服器可能會拒絕認證並要求新的認證。

  9. HTTP 伺服器可能會拒絕使用者名稱和密碼;它可能會告訴 WebView2 控制項「不允許您取得該 URI/檔」。

  10. WebView2 控制項會呈現 HTTP 伺服器傳回的錯誤頁面。 轉譯會在事件和 DOMContentLoaded 事件之間 ContentLoading 發生。

  11. HTTP 伺服器可能會接受驗證認證,並傳回要求的檔。

  12. WebView2 控制項會轉譯傳回的檔。 The rendering occurs between the ContentLoading event and DOMContentLoaded event.

範例程式碼:提供事先已知認證的應用程式

下列簡化範例顯示主應用程式提供認證 (事先已知的使用者名稱和密碼) 。 此範例是 WebView2Samples 存放庫 > WebView2APISample > ScenarioAuthentication.cpp中稍微修改過的程式碼版本。

這個範例並不實際,因為:

  • 在實務上,您會提示使用者輸入使用者名稱和密碼,而不是將它們硬式編碼,例如 "user""pass"
  • 此程式碼是同步的,但您可能會改用非同步程式碼。

如需更實際的程式碼,請參閱後續章節。

// Prerequisite: Before using this code, make sure you read the section "Use HTTPS 
// for sending credentials" in this article.
    webView.CoreWebView2.BasicAuthenticationRequested += delegate (
       object sender, 
       CoreWebView2BasicAuthenticationRequestedEventArgs args)
    {
        args.Response.UserName = "user";
        args.Response.Password = "pass";
    };

Api:

範例程式碼:提示使用者輸入認證

此範例示範主應用程式提示使用者輸入認證 (使用者名稱和密碼) ,並使用非同步程式碼。

此範例是以上述範例為基礎,方法是新增下列功能:

  • 顯示對話方塊,提示使用者輸入其使用者名稱和密碼。
  • 在 自變 GetDeferral 量上 event 呼叫 方法。
// Prerequisite: Before using this code, make sure you read the section "Use HTTPS 
// for sending credentials" in this article.
webView.CoreWebView2.BasicAuthenticationRequested += delegate (
    object sender, 
    CoreWebView2BasicAuthenticationRequestedEventArgs args)
{
    // We need to show UI asynchronously so we obtain a deferral.
    // A deferral will delay the CoreWebView2 from
    // examining the properties we set on the event args until
    // after we call the Complete method asynchronously later.
    // This gives us time to asynchronously show UI.
    CoreWebView2Deferral deferral = args.GetDeferral();

    // We avoid potential reentrancy from running a message loop in the
    // event handler by showing our download dialog later when we
    // complete the deferral asynchronously.
    System.Threading.SynchronizationContext.Current.Post((_) =>
    {
        using (deferral)
        {
            // When prompting the end user for authentication its important
            // to show them the URI or origin of the URI that is requesting
            // authentication so the end user will know who they are giving
            // their username and password to.

            // Its also important to display the challenge to the end user
            // as it may have important site specific information for the
            // end user to provide the correct username and password.

            // Use an app or UI framework method to get input from the end user.
            TextInputDialog dialog = new TextInputDialog(
                title: "Authentication Request",
                description: "Authentication request from " + args.Uri + "\r\n" +
                    "Challenge: " + args.Challenge,
                defaultInput: "username\r\npassword");
            bool userNameAndPasswordSet = false;

            if (dialog.ShowDialog().GetValueOrDefault(false))
            {
                string[] userNameAndPassword = dialog.Input.Text.Split(
                    new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                if (userNameAndPassword.Length > 1)
                {
                    args.Response.UserName = userNameAndPassword[0];
                    args.Response.Password = userNameAndPassword[1];
                    userNameAndPasswordSet = true;
                }
            }

            // If we didn't get a username and password from the end user then
            // we cancel the authentication request and don't provide any
            // authentication.
            if (!userNameAndPasswordSet)
            {
                args.Cancel = true;
            }
        }
    }, null);
};

APIs:

導覽的運作方式

本節提供導覽運作方式的選擇性背景資訊。

會對應至多個導覽事件。 透過 導覽,我們在這裡表示每次重試,從上述圖表的方塊開始 NavigationStartingNavigationCompleted 透過 方塊。

當新的導覽開始時,會指派新的導覽識別碼。 針對新的導覽,HTTP 伺服器會提供 WebView2 控制項檔。 這是「有檔」導覽。

在導覽過程中,WebView2 控制項會將對應的頁面轉譯 (要求的頁面或錯誤頁面,以 HTTP 伺服器) 傳回者為准,而「成功」或「失敗」結果會引發成功或失敗的 NavigationCompleted 事件。

For more information, see Navigation events for WebView2 apps.

流程中有兩種導覽:

  • 「伺服器要求驗證」導覽。
  • 「伺服器提供 WebView2 控制項檔」導覽。

在第一種導覽類型之後,伺服器已要求進行驗證,且應用程式必須使用新的導覽識別碼) ,再次嘗試這種導覽 (。 新的導覽會使用主應用程式從事件引數回應物件取得的任何內容。

HTTP 伺服器可能需要 HTTP 驗證。 在此情況下,會有第一個 覽,其中包含上面所列的導覽事件。 HTTP 伺服器會傳回 401 或 407 HTTP 回應,因此 NavigationCompleted 事件有對應的失敗。 然後,WebView2 會轉譯空白頁面並引發 BasicAuthenticationRequested 事件,這可能會提示使用者輸入認證。

BasicAuthenticationRequested如果取消事件,則沒有後續的導覽,且 WebView2 會保留以顯示空白頁面。

BasicAuthenticationRequested如果事件未取消,WebView2 會再次執行初始導覽,但這次會使用任何提供的認證。 您會再次看到與之前相同的所有導覽事件。

如果 HTTP 伺服器不接受認證,流覽會再次失敗,並顯示 401 或 407。 在此情況下, CoreWebView2 類別實例會再次引發 BasicAuthenticationRequested 事件,並如上所示繼續流覽。

如果 HTTP 伺服器接受認證,則導覽會成功。 如果 HTTP 伺服器拒絕驗證,導覽會失敗 (伺服器通常會傳回錯誤頁面) 。

事件前後的 BasicAuthenticationRequested 導覽是不同的導覽,而且具有不同的流覽識別碼。

導覽 event args 具有屬性: NavigationId 。 會 NavigationId 將對應至單一導覽的導覽事件系結在一起。 在 NavigationId 每次導覽期間保持不變,例如重試。 在下一次通過事件流程期間,會使用不同的 NavigationId

API 參考概觀

另請參閱