設定呼叫 Web API 的行動應用程式

建立應用程式之後,您將瞭解如何使用應用程式註冊參數來設定程序代碼。 行動應用程式呈現一些與融入其建立架構相關的複雜度。

支援行動應用程式的 Microsoft 連結庫

下列 Microsoft 連結庫支援行動應用程式:

平台 項目開啟
GitHub
套件 取得
啟動
登入使用者 存取 Web API 正式推出 (GA)
公開預覽1
Android (Java) MSAL Android MSAL 快速入門 連結庫可以要求使用者登入的標識碼令牌。 連結庫可以要求受保護 Web API 的存取令牌。 GA
Android (Kotlin) MSAL Android MSAL 連結庫可以要求使用者登入的標識碼令牌。 連結庫可以要求受保護 Web API 的存取令牌。 GA
iOS (Swift/Obj-C) 適用於 iOS 和 macOS 的 MSAL MSAL 教學課程 連結庫可以要求使用者登入的標識碼令牌。 連結庫可以要求受保護 Web API 的存取令牌。 GA
Xamarin (.NET) MSAL.NET Microsoft.Identity.Client 連結庫可以要求使用者登入的標識碼令牌。 連結庫可以要求受保護 Web API 的存取令牌。 GA

1在線服務的通用授權條款適用於公開預覽中的連結庫。

具現化應用程式

Android

行動應用程式會使用類別 PublicClientApplication 。 以下說明如何具現化它:

PublicClientApplication sampleApp = new PublicClientApplication(
                    this.getApplicationContext(),
                    R.raw.auth_config);

iOS

iOS 上的行動應用程式需要具現化 類別 MSALPublicClientApplication 。 若要具現化 類別,請使用下列程序代碼。

NSError *msalError = nil;

MSALPublicClientApplicationConfig *config = [[MSALPublicClientApplicationConfig alloc] initWithClientId:@"<your-client-id-here>"];
MSALPublicClientApplication *application = [[MSALPublicClientApplication alloc] initWithConfiguration:config error:&msalError];
let config = MSALPublicClientApplicationConfig(clientId: "<your-client-id-here>")
if let application = try? MSALPublicClientApplication(configuration: config){ /* Use application */}

其他 MSALPublicClientApplicationConfig 屬性 可以覆寫預設授權單位、指定重新導向 URI,或變更 MSAL 令牌快取的行為。

Xamarin 或 UWP

本節說明如何具現化 Xamarin.iOS、Xamarin.Android 和 UWP 應用程式的應用程式。

具現化應用程式

在 Xamarin 或 UWP 中,具現化應用程式最簡單的方式是使用下列程式代碼。 在此程式代碼中, ClientId 是已註冊應用程式的 GUID。

var app = PublicClientApplicationBuilder.Create(clientId)
                                        .Build();

其他 With<Parameter> 方法會設定 UI 父系、覆寫預設授權單位、指定遙測的用戶端名稱和版本、指定重新導向 URI,以及指定要使用的 HTTP 處理站。 例如,HTTP 處理站可用來處理 Proxy,以及指定遙測和記錄。

下列各節提供有關具現化應用程式的詳細資訊。

指定父 UI、視窗或活動

在Android上,先傳遞父活動,再執行互動式驗證。 在 iOS 上,當您使用訊息代理程式時,傳入 ViewController。 在UWP上,您可能會想要傳入父視窗。 當您取得令牌時,您會將其傳入。 但是當您建立應用程式時,您也可以將回呼指定為傳回 的 UIParent委派。

IPublicClientApplication application = PublicClientApplicationBuilder.Create(clientId)
  .ParentActivityOrWindowFunc(() => parentUi)
  .Build();

在 Android 上,我們建議您使用 CurrentActivityPlugin。 產生的產生器 PublicClientApplication 程式代碼看起來像下列範例:

// Requires MSAL.NET 4.2 or above
var pca = PublicClientApplicationBuilder
  .Create("<your-client-id-here>")
  .WithParentActivityOrWindow(() => CrossCurrentActivity.Current)
  .Build();
尋找更多應用程式建置參數

如需 上 PublicClientApplicationBuilder所有可用方法的清單,請參閱 方法清單

如需 中 PublicClientApplicationOptions公開之所有選項的描述,請參閱 參考檔

Xamarin iOS 的工作

如果您在 Xamarin iOS 上使用 MSAL.NET,請執行下列工作。

如需詳細資訊,請參閱 Xamarin iOS 考慮

適用於 iOS 和 macOS 的 MSAL 工作

當您針對 iOS 和 macOS 使用 MSAL 時,這些工作是必要的:

Xamarin.Android 的工作

如果您使用 Xamarin.Android,請執行下列工作:

如需詳細資訊,請參閱 Xamarin.Android 考慮

如需 Android 上瀏覽器的考慮,請參閱 MSAL.NET 的 Xamarin.Android 特定考慮。

UWP 的工作

在UWP上,您可以使用公司網路。 下列各節說明您應該在公司案例中完成的工作。

如需詳細資訊,請參閱 使用 MSAL.NET 的 UWP 特定考慮。

設定應用程式以使用訊息代理程式

在 Android 和 iOS 上,訊息代理程式會啟用:

  • 單一登錄 (SSO):您可以針對使用 Microsoft Entra ID 註冊的裝置使用 SSO。 當您使用 SSO 時,您的使用者不需要登入每個應用程式。
  • 裝置識別:此設定會啟用與 Microsoft Entra 裝置相關的條件式存取原則。 驗證程式會使用裝置加入工作場所時所建立的裝置憑證。
  • 應用程式識別驗證:當應用程式呼叫訊息代理程式時,它會傳遞其重新導向URL。 然後訊息代理程式會驗證它。

在 Xamarin 上啟用訊息代理程式

若要在 Xamarin 上啟用訊息代理程式,請在呼叫 PublicClientApplicationBuilder.CreateApplication 方法時使用 WithBroker() 參數。 根據預設, .WithBroker() 會設定為 true。

若要啟用 Xamarin.iOS 的代理驗證,請遵循本文中的 Xamarin.iOS 一節 中的步驟。

啟用適用於 Android 的 MSAL 訊息代理程式

如需在 Android 上啟用訊息代理程式的相關信息,請參閱 Android 上的代理驗證。

啟用適用於 iOS 和 macOS 之 MSAL 的訊息代理程式

在適用於 iOS 和 macOS 的 MSAL 中,預設會針對 Microsoft Entra 案例啟用代理驗證。

下列各節提供針對 Xamarin.iOS 的 MSAL 或適用於 iOS 和 macOS 的 MSAL 設定應用程式以進行代理驗證支援的指示。 在兩組指示中,有些步驟不同。

啟用 Xamarin iOS 的代理驗證

請遵循本節中的步驟,讓您的 Xamarin.iOS 應用程式能夠與 Microsoft Authenticator 應用程式交談。

步驟 1:啟用訊息代理程序支援

代理程式支援預設為停用。 您可以針對個別 PublicClientApplication 類別啟用它。 透過 建立 類別PublicClientApplicationBuilder時,WithBroker()PublicClientApplication請使用 參數。 WithBroker()參數預設會設定為 true。

var app = PublicClientApplicationBuilder
                .Create(ClientId)
                .WithBroker()
                .WithReplyUri(redirectUriOnIos) // $"msauth.{Bundle.Id}://auth" (see step 6 below)
                .Build();

步驟 2:更新 AppDelegate 以處理回呼

MSAL.NET 呼叫訊息代理程式時,訊息代理程序接著會回呼您的應用程式。 它會使用 AppDelegate.OpenUrl 方法回呼。 因為 MSAL 會等候訊息代理程式發出的回應,因此您的應用程式必須配合才能呼叫 MSAL.NET。 您可以藉由更新 AppDelegate.cs 檔案來覆寫 方法來設定此行為,如下列程式代碼所示。

public override bool OpenUrl(UIApplication app, NSUrl url,
                             string sourceApplication,
                             NSObject annotation)
{
 if (AuthenticationContinuationHelper.IsBrokerResponse(sourceApplication))
 {
  AuthenticationContinuationHelper.SetBrokerContinuationEventArgs(url);
  return true;
 }
 else if (!AuthenticationContinuationHelper.SetAuthenticationContinuationEventArgs(url))
 {
  return false;
 }
 return true;
}

每次啟動應用程式時,都會叫用這個方法。 您可以處理來自訊息代理程式的回應,並完成 MSAL.NET 啟動的驗證程式。

步驟 3:設定 UIViewController()

針對 Xamarin iOS,您通常不需要設定物件視窗。 但在此情況下,您應該設定它,以便您可以從訊息代理程式傳送和接收回應。 若要設定物件視窗,請在 中 AppDelegate.cs設定 ViewController

若要設定物件視窗,請遵循下列步驟:

  1. 在 中 AppDelegate.cs,將設定 App.RootViewController 為新的 UIViewController()。 這個設定可確保對訊息代理程式的呼叫包含 UIViewController。 如果未正確設定,您可能會收到此錯誤:

    "uiviewcontroller_required_for_ios_broker":"UIViewController is null, so MSAL.NET cannot invoke the iOS broker. See https://aka.ms/msal-net-ios-broker."

  2. 在呼叫中 AcquireTokenInteractive ,使用 .WithParentActivityOrWindow(App.RootViewController)。 傳入您將使用之物件視窗的參考。 以下是範例:

    App.cs 中:

       public static object RootViewController { get; set; }
    

    AppDelegate.cs 中:

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

    在呼叫中 AcquireToken

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

步驟 4︰註冊 URL 配置

MSAL.NET 使用 URL 來叫用訊息代理程式,然後將訊息代理程式回應傳回您的應用程式。 若要完成來回行程,請在 檔案中 Info.plist 註冊應用程式的URL配置。

若要註冊應用程式的 URL 配置,請遵循下列步驟:

  1. 前置 CFBundleURLSchemes 詞為 msauth

  2. 將 新增 CFBundleURLName 至結尾。 請遵循下列模式:

    $"msauth.(BundleId)"

    在這裡, BundleId 可唯一識別您的裝置。 例如,如果 BundleIdyourcompany.xforms,則您的 URL 設定為 msauth.com.yourcompany.xforms

    當應用程式收到訊息代理程序回應時,此 URL 配置將會成為可唯一識別您應用程式的重新導向 URI 的一部分。

     <key>CFBundleURLTypes</key>
        <array>
          <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>com.yourcompany.xforms</string>
            <key>CFBundleURLSchemes</key>
            <array>
              <string>msauth.com.yourcompany.xforms</string>
            </array>
          </dict>
        </array>
    

步驟 5:新增至 LSApplicationQueriesSchemes 區段

MSAL 會使用 –canOpenURL: 來檢查代理程式是否已安裝在裝置上。 在 iOS 9 中,Apple 鎖定了應用程式可以查詢的配置。

將 新增 msauthv2LSApplicationQueriesSchemes 檔案的 Info.plist 區段,如下列程式代碼範例所示:

<key>LSApplicationQueriesSchemes</key>
    <array>
      <string>msauthv2</string>
    </array>

適用於 iOS 和 macOS 的 MSAL 代理驗證

Microsoft Entra 案例預設會啟用代理驗證。

步驟 1:更新 AppDelegate 以處理回呼

當 iOS 和 macOS 的 MSAL 呼叫訊息代理程式時,訊息代理程式會使用 openURL 方法回呼您的應用程式。 因為 MSAL 會等候訊息代理程式發出的回應,因此您的應用程式必須配合呼叫 MSAL。 如下列程式代碼範例所示,更新 AppDelegate.m 檔案以覆寫 方法,以設定這項功能。

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
    return [MSALPublicClientApplication handleMSALResponse:url
                                         sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]];
}
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

        guard let sourceApplication = options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String else {
            return false
        }

        return MSALPublicClientApplication.handleMSALResponse(url, sourceApplication: sourceApplication)
    }

如果您在 iOS 13 或更新版本上採用UISceneDelegate,請將 MSAL 回呼放在 ,scene:openURLContexts:UISceneDelegate而不是 。 每個 URL 都必須只呼叫 MSAL handleMSALResponse:sourceApplication: 一次。

如需詳細資訊,請參閱 Apple 檔

步驟 2:註冊 URL 配置

適用於 iOS 和 macOS 的 MSAL 會使用 URL 來叫用訊息代理程式,然後將訊息代理程式回應傳回您的應用程式。 若要完成來回行程,請在 檔案中 Info.plist 註冊應用程式的URL配置。

若要為您的應用程式註冊設定:

  1. 在自訂網址設定前面加上 msauth

  2. 將套件組合識別碼新增至配置結尾。 請遵循下列模式:

    $"msauth.(BundleId)"

    在這裡, BundleId 可唯一識別您的裝置。 例如,如果 BundleIdyourcompany.xforms,則您的 URL 設定為 msauth.com.yourcompany.xforms

    當應用程式收到訊息代理程序回應時,此 URL 配置將會成為可唯一識別您應用程式的重新導向 URI 的一部分。 請確定已為您的應用程式註冊格式 msauth.(BundleId)://auth 的重新導向 URI。

    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>msauth.[BUNDLE_ID]</string>
            </array>
        </dict>
    </array>
    

步驟 3:新增 LSApplicationQueriesSchemes

新增 LSApplicationQueriesSchemes 以允許呼叫 Microsoft Authenticator 應用程式,如果已安裝。

注意

使用 Xcode 11 和更新版本編譯應用程式時,需要配置 msauthv3

以下是如何新增 LSApplicationQueriesSchemes的範例:

<key>LSApplicationQueriesSchemes</key>
<array>
  <string>msauthv2</string>
  <string>msauthv3</string>
</array>

Xamarin.Android 的代理驗證

如需在 Android 上啟用訊息代理程式的詳細資訊,請參閱 Xamarin.Android 上的代理驗證。

下一步

請移至此案例中的下一篇文章, 取得令牌