將使用訊息代理程式從 ADAL.NET 移轉至 MSAL.NET

如果您有 Xamarin Android 應用程式目前使用適用於 .NET 的 Azure Active Directory 驗證連結庫(ADAL.NET)和 驗證代理人,是時候移轉至 適用於 .NET 的 Microsoft 驗證連結庫 (MSAL.NET)。

必要條件

步驟 1︰啟用訊息代理程式

目前的 ADAL 程式碼:MSAL 對應項目:
在 ADAL.NET 中,代理程序支援是以個別驗證內容為基礎啟用。

若要呼叫訊息代理程式,您必須在建構函式中PlatformParameters將 設定useBrokertrue

public PlatformParameters(
        Activity callerActivity,
        bool useBroker)

在 Android 的平臺特定頁面轉譯器程式代碼中,您會將 useBroker 旗標設定為 true:

page.BrokerParameters = new PlatformParameters(
        this,
        true,
        PromptBehavior.SelectAccount);

然後,將參數包含在取得權杖呼叫中:

AuthenticationResult result =
        await
            AuthContext.AcquireTokenAsync(
                Resource,
                ClientId,
                new Uri(RedirectURI),
                platformParameters)
                .ConfigureAwait(false);
在 MSAL.NET 中,會根據 PublicClientApplication 基礎啟用訊息代理程式支援。

WithBroker()使用 參數 (預設設定為 true) 來呼叫訊息代理程式:

var app = PublicClientApplicationBuilder
                .Create(ClientId)
                .WithBroker()
                .WithRedirectUri(redirectUriOnAndroid)
                .Build();

然後,在 AcquireToken 呼叫中:

result = await app.AcquireTokenInteractive(scopes)
             .WithParentActivityOrWindow(App.RootViewController)
             .ExecuteAsync();

步驟 2:設定活動

在 ADAL.NET 中,您已傳入活動(通常是 MainActivity),作為 PlatformParameters 的一部分,如步驟 1:啟用訊息代理程式所示

MSAL.NET 也會使用活動,但在沒有訊息代理程序的情況下,在一般 Android 使用量中則不需要此活動。 若要使用訊息代理程式,請將活動設定為從訊息代理程式傳送和接收回應。

目前的 ADAL 程式碼:MSAL 對應項目:
活動會傳遞至Android特定平臺中的 PlatformParameters。
page.BrokerParameters = new PlatformParameters(
          this,
          true,
          PromptBehavior.SelectAccount);

在 MSAL.NET 中,執行兩件事來設定 Android 的活動:

  1. MainActivity.cs中,將 設定 App.RootViewControllerMainActivity ,以確保有活動與訊息代理程式呼叫。

    如果未正確設定,您可能會收到此錯誤: "Activity_required_for_android_broker":"Activity is null, so MSAL.NET cannot invoke the Android broker. See https://aka.ms/Brokered-Authentication-for-Android"

  2. 在 AcquireTokenInteractive 呼叫上,使用 .WithParentActivityOrWindow(App.RootViewController) ,並將 參考傳入您將使用的活動。 此範例將使用MainActivity。

例如:

App.cs

   public static object RootViewController { get; set; }

MainActivity.cs

   LoadApplication(new App());
   App.RootViewController = this;

在 AcquireToken 呼叫中:

result = await app.AcquireTokenInteractive(scopes)
             .WithParentActivityOrWindow(App.RootViewController)
             .ExecuteAsync();

下一步

如需搭配 Xamarin 使用 MSAL.NET 時 Android 特定考慮的詳細資訊,請參閱 Xamarin Android 搭配 MSAL.NET 的設定需求和疑難解答秘訣。