Share via


Web 驗證器

流覽範例。 流覽範例

本文說明如何使用 .NET 多平臺應用程式 UI (.NET MAUI) IWebAuthenticator 介面。 此介面可讓您啟動瀏覽器型驗證流程,以接聽註冊至應用程式之特定 URL 的回呼。

介面的預設實作 IWebAuthenticator 可透過 WebAuthenticator.Default 屬性取得。 IWebAuthenticator介面和WebAuthenticator類別都包含在 命名空間中Microsoft.Maui.Authentication

概觀

許多應用程式都需要新增用戶驗證,這通常表示讓用戶能夠登入其現有的 Microsoft、Facebook、Google 或 Apple 登入帳戶。

提示

Microsoft 驗證連結庫 (MSAL) 提供絕佳的周全解決方案,將驗證新增至您的應用程式。

如果您有興趣使用自己的 Web 服務進行驗證,則可以使用 WebAuthenticator 來實作用戶端功能。

為何使用伺服器後端

許多驗證提供者已移至只提供明確或雙腿驗證流程,以確保更好的安全性。 這表示您需要 來自提供者的客戶端密碼 ,才能完成驗證流程。 不幸的是,行動裝置應用程式不是儲存秘密的絕佳位置,而且任何儲存在行動應用程式的程式代碼、二進位檔或其他檔案中,都被視為不安全的地方。

最佳做法是使用 Web 後端作為行動應用程式與驗證提供者之間的中間層。

重要

我們強烈建議不要使用較舊的僅限行動裝置驗證連結庫和模式,這些連結庫和模式不會在驗證流程中利用 Web 後端,因為其固有缺少儲存用戶端密碼的安全性。

開始使用

若要存取下列 WebAuthenticator 平臺特定設定的功能,

Android 需要 意圖篩選 設定來處理回呼 URI。 這是藉由繼承自 WebAuthenticatorCallbackActivity 類別來完成:

using Android.App;
using Android.Content.PM;

namespace YourNameSpace;

[Activity(NoHistory = true, LaunchMode = LaunchMode.SingleTop, Exported = true)]
[IntentFilter(new[] { Android.Content.Intent.ActionView },
              Categories = new[] { Android.Content.Intent.CategoryDefault, Android.Content.Intent.CategoryBrowsable },
              DataScheme = CALLBACK_SCHEME)]
public class WebAuthenticationCallbackActivity : Microsoft.Maui.Authentication.WebAuthenticatorCallbackActivity
{
    const string CALLBACK_SCHEME = "myapp";

}

如果您的項目目標 Android 版本設定為 Android 11(R API 30)或更高版本,您必須使用使用 Android 套件可見性需求的查詢來更新 Android 指令清單

[平臺/Android/AndroidManifest.xml] 檔案中,在 節點中manifest新增下列queries/intent節點:

<queries>
  <intent>
    <action android:name="android.support.customtabs.action.CustomTabsService" />
  </intent>
</queries>

使用 WebAuthenticator

API 主要包含單一方法, AuthenticateAsync採用兩個參數:

  1. 用來啟動網頁瀏覽器流程的 URL。
  2. 流程預期最終會回呼的 URI,該 URI 會向您的應用程式註冊。

結果是 『WebAuthenticatorResult,其中包含從回呼 URI 剖析的任何查詢參數:

try
{
    WebAuthenticatorResult authResult = await WebAuthenticator.Default.AuthenticateAsync(
        new Uri("https://mysite.com/mobileauth/Microsoft"),
        new Uri("myapp://"));

    string accessToken = authResult?.AccessToken;

    // Do something with the token
}
catch (TaskCanceledException e)
{
    // Use stopped auth
}

WebAuthenticator API 會負責在瀏覽器中啟動 URL,並等到收到回呼為止:

一般 Web 驗證流程。

如果使用者在任何時間點取消流程, TaskCanceledException 則會擲回 。

私人驗證會話

iOS 13 引進了暫時的網頁瀏覽器 API,讓開發人員以私人方式啟動驗證會話。 這可讓開發人員要求驗證會話之間沒有共用 Cookie 或瀏覽數據,而且每次都會是全新的登入會話。 這可透過 WebAuthenticatorOptions 傳遞至 方法的參數 AuthenticateAsync 來取得:

try
{
    WebAuthenticatorResult authResult = await WebAuthenticator.Default.AuthenticateAsync(
        new WebAuthenticatorOptions()
        {
            Url = new Uri("https://mysite.com/mobileauth/Microsoft"),
            CallbackUrl = new Uri("myapp://"),
            PrefersEphemeralWebBrowserSession = true
        });

    string accessToken = authResult?.AccessToken;

    // Do something with the token
}
catch (TaskCanceledException e)
{
    // Use stopped auth
}

平台差異

本節說明與 Web 驗證 API 的平臺特定差異。

每當可用時,就會使用自定義索引 標籤,否則系統會使用系統瀏覽器作為後援。

Apple 登入

根據 Apple 的評論指導方針,如果您的 Apple 應用程式使用任何社交登入服務進行驗證,它也必須提供 Apple 登入作為選項。 若要將 Apple 登入新增至您的應用程式,您必須將使用 Apple 權利登入新增至您的應用程式。 此權利是使用 com.apple.developer.applesigninArray 別的 String索引鍵來定義:

<key>com.apple.developer.applesignin</key>
<array>
  <string>Default</string>
</array>

如需詳細資訊,請參閱 在 developer.apple.com 上使用 Apple 權利 登入。

針對 iOS 13 和更新版本,呼叫 AppleSignInAuthenticator.AuthenticateAsync 方法。 這會使用原生 Apple 登入 API,讓使用者在這些裝置上獲得最佳體驗。 例如,您可以撰寫共享程式碼,在運行時間使用正確的 API:

var scheme = "..."; // Apple, Microsoft, Google, Facebook, etc.
var authUrlRoot = "https://mysite.com/mobileauth/";
WebAuthenticatorResult result = null;

if (scheme.Equals("Apple")
    && DeviceInfo.Platform == DevicePlatform.iOS
    && DeviceInfo.Version.Major >= 13)
{
    // Use Native Apple Sign In API's
    result = await AppleSignInAuthenticator.AuthenticateAsync();
}
else
{
    // Web Authentication flow
    var authUrl = new Uri($"{authUrlRoot}{scheme}");
    var callbackUrl = new Uri("myapp://");

    result = await WebAuthenticator.Default.AuthenticateAsync(authUrl, callbackUrl);
}

var authToken = string.Empty;

if (result.Properties.TryGetValue("name", out string name) && !string.IsNullOrEmpty(name))
    authToken += $"Name: {name}{Environment.NewLine}";

if (result.Properties.TryGetValue("email", out string email) && !string.IsNullOrEmpty(email))
    authToken += $"Email: {email}{Environment.NewLine}";

// Note that Apple Sign In has an IdToken and not an AccessToken
authToken += result?.AccessToken ?? result?.IdToken;

提示

針對非 iOS 13 裝置,這會啟動 Web 驗證流程,這也可用來在 Android 和 Windows 裝置上啟用 Apple 登入。 您可以在 iOS 模擬器上登入 iCloud 帳戶,以測試 Apple 登入。

ASP.NET 核心伺服器後端

WebAuthenticator您可以使用 API 搭配任何 Web 後端服務。 若要將它與 ASP.NET 核心應用程式搭配使用,請使用下列步驟設定 Web 應用程式:

  1. 在 ASP.NET Core Web 應用程式中設定外部 社交驗證提供者
  2. 在呼叫中將 [預設驗證配置] 設定為 CookieAuthenticationDefaults.AuthenticationScheme.AddAuthentication()
  3. 在您的Startup.cs呼叫中使用.AddCookie().AddAuthentication()
  4. 所有提供者都必須使用 來 .SaveTokens = true;設定。
services.AddAuthentication(o =>
    {
        o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    })
    .AddCookie()
    .AddFacebook(fb =>
    {
        fb.AppId = Configuration["FacebookAppId"];
        fb.AppSecret = Configuration["FacebookAppSecret"];
        fb.SaveTokens = true;
    });

提示

如果您想要包含 Apple 登入,您可以使用 AspNet.Security.OAuth.Apple NuGet 套件。 您可以檢視完整的 Startup.cs範例

新增自訂行動驗證控制器

使用行動驗證流程時,您通常會直接啟動流程給使用者所選擇的提供者。 例如,按兩下應用程式登入畫面上的 [Microsoft] 按鈕。 若要結束驗證流程,請務必在特定回呼 URI 將相關信息傳回至您的應用程式。

若要達成此目的,請使用自定義 API 控制器:

[Route("mobileauth")]
[ApiController]
public class AuthController : ControllerBase
{
    const string callbackScheme = "myapp";

    [HttpGet("{scheme}")] // eg: Microsoft, Facebook, Apple, etc
    public async Task Get([FromRoute]string scheme)
    {
        // 1. Initiate authentication flow with the scheme (provider)
        // 2. When the provider calls back to this URL
        //    a. Parse out the result
        //    b. Build the app callback URL
        //    c. Redirect back to the app
    }
}

此控制器的目的是推斷應用程式所要求的配置(提供者),並啟動與社交提供者的驗證流程。 當提供者回呼至 Web 後端時,控制器會剖析結果,並使用參數重新導向至應用程式的回呼 URI。

有時候,您可能會想要傳回提供者 access_token 回到應用程式等數據,而您可以透過回呼 URI 的查詢參數來執行此動作。 或者,您可能想要改為在伺服器上建立自己的身分識別,並將您自己的令牌傳回應用程式。 這個部分的用途和方式由您決定!

查看 完整的控制器範例

注意

上述範例示範如何從第三方驗證 (即:OAuth) 提供者傳回存取令牌。 若要取得令牌,您可以使用 來授權 Web 後端本身的 Web 要求,您應該在 Web 應用程式中建立自己的令牌,並改為傳回該令牌。 ASP.NET 核心驗證概觀提供 ASP.NET Core 中進階驗證案例的詳細資訊。