共用方式為


教學課程:準備您的 iOS (Swift) 應用程式以進行驗證

這是教學課程系列中的第二個教學課程,示範如何將適用於iOS和macOS的 Microsoft 驗證連結庫 (MSAL) 新增至iOS Swift 應用程式。

開始之前,請使用 選擇此頁面頂端的租用戶類型 選取器,以選取租用戶類型。 Microsoft Entra ID 提供兩種租戶組態,內部 員工 和 外部。 工作人員租戶配置適用於你的員工、內部應用和其他組織資源。 外部租戶用於客戶導向的應用程式。

在本教學課程中,您會:

  • 將 MSAL 架構新增至 iOS (Swift) 應用程式。
  • 建立 SDK 實例。
  • 設定 Xcode 項目設定。

先決條件

將 MSAL 架構新增至 iOS (Swift) 應用程式

選擇下列其中一種方式,在您的應用程式中安裝 MSAL 連結庫:

CocoaPods

  1. 如果您使用 CocoaPods,請先在專案的 .xcodeproj 檔案中建立名為 podfile 的空白檔案,以安裝 MSAL。 將下列內容新增至 podfile

    use_frameworks!
    
    target '<your-target-here>' do
       pod 'MSAL'
    end
    
  2. <your-target-here> 取代為您的專案名稱。

  3. 在終端機視窗中,流覽至包含您建立並執行 pod installpodfi le 的資料夾,以安裝 MSAL 連結庫。

  4. 關閉 Xcode 並開啟 <your project name>.xcworkspace,以在 Xcode 中重載專案。

迦太基

如果您使用 Carthage,請將它新增至您的 Cartfile以安裝 MSAL

github "AzureAD/microsoft-authentication-library-for-objc" "master"

從終端機視窗中,在與已更新 Cartfile相同的目錄中,執行下列命令,讓 Carthage 更新專案中的相依性。

iOS:

carthage update --platform iOS

macOS:

carthage update --platform macOS

手動

您也可以使用 Git Submodule,或查看最新版本,以作為應用程式中的架構使用。

新增應用程式註冊

接下來,我們會將您的應用程式註冊新增至您的程序代碼。

首先,將下列 import 語句新增至 ViewController.swift 檔案頂端,AppDelegate.swiftSceneDelegate.swift

import MSAL

接下來,將下列程式代碼新增至 ViewController.swift,再 viewDidLoad()

// Update the below to your client ID. The below is for running the demo only
let kClientID = "Your_Application_Id_Here"
let kGraphEndpoint = "https://graph.microsoft.com/" // the Microsoft Graph endpoint
let kAuthority = "https://login.microsoftonline.com/common" // this authority allows a personal Microsoft account and a work or school account in any organization's Azure AD tenant to sign in

let kScopes: [String] = ["user.read"] // request permission to read the profile of the signed-in user

var accessToken = String()
var applicationContext : MSALPublicClientApplication?
var webViewParameters : MSALWebviewParameters?
var currentAccount: MSALAccount?

您唯一需要修改的值是指派給 kClientID 的值,使其成為 應用程式識別碼。 此值是您在本教學課程開頭的步驟中儲存的 MSAL 組態數據的一部分,以註冊應用程式。

建立 SDK 實例

若要在專案中建立 MSAL 實例,請遵循下列步驟:

ViewController 類別中,新增 initMSAL 方法:

    func initMSAL() throws {

        guard let authorityURL = URL(string: kAuthority) else {
            self.updateLogging(text: "Unable to create authority URL")
            return
        }

        let authority = try MSALAADAuthority(url: authorityURL)

        let msalConfiguration = MSALPublicClientApplicationConfig(clientId: kClientID, redirectUri: nil, authority: authority)
        self.applicationContext = try MSALPublicClientApplication(configuration: msalConfiguration)
        self.initWebViewParams()
    }

仍在 ViewController 類別中,並在 initMSAL 方法之後,新增 initWebViewParams 方法:

iOS 程式代碼:

func initWebViewParams() {
        self.webViewParameters = MSALWebviewParameters(authPresentationViewController: self)
    }

macOS 程式代碼:

func initWebViewParams() {
        self.webViewParameters = MSALWebviewParameters()
    }

設定 Xcode 項目設定

將新的金鑰鏈群組新增至專案,簽署 & 功能。 密鑰鏈群組應該在 iOS 上 com.microsoft.adalcache,並在 macOS 上 com.microsoft.identity.universalstorage

Xcode UI,顯示金鑰鏈群組的設定方式。

僅限 iOS,請設定 URL 配置

在此步驟中,您將註冊 CFBundleURLSchemes,讓用戶可以在登入后重新導向回應用程式。 順便說一句,LSApplicationQueriesSchemes 也可讓您的應用程式使用 Microsoft Authenticator。

在 Xcode 中,開啟 Info.plist 作為原始碼檔案,並在 <dict> 區段中新增下列內容。 將 [BUNDLE_ID] 替換為您先前使用的值。 如果您下載代碼,套件組合識別碼是 com.microsoft.identitysample.MSALiOS。 如果您要建立自己的專案,請在 Xcode 中選取項目,然後開啟 [[一般] 索引標籤。套件組合標識碼會出現在 [身分識別] 區段中。

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

僅適用於 macOS,設定應用程式沙盒

  1. 移至 [Xcode 項目設定] >[功能] 索引標籤>應用程式沙箱
  2. 選取 [傳出連線(用戶端)] 複選框。

後續步驟

這是教學課程系列中的第二個教學課程,示範如何將適用於iOS和macOS的 Microsoft 驗證連結庫 (MSAL) 新增至iOS Swift 應用程式。

開始之前,請使用此頁面頂端的 租用戶類型選擇器 來選取租用戶類型。 Microsoft Entra ID 提供兩個租用戶組態,員工外部。 員工租戶配置適用於您的員工、內部應用程式和其他組織資源。 外部租戶是針對客戶端應用程式的。

在本教學課程中,您會;

  • 將 MSAL 架構新增至 iOS (Swift) 應用程式。
  • 建立 SDK 實例。

先決條件

  • Xcode
  • 如果您尚未這麼做,請遵循 教學課程:註冊和設定 iOS(Swift)行動應用程式 的指示,並在外部租戶中註冊應用程式。 請確定您完成下列步驟:
    • 註冊應用程式。
    • 新增平臺重新導向 URL。
    • 啟用公用用戶端流程。
    • Microsoft Graph 的委派許可權。
  • iOS (Swift) 專案。

將 MSAL 架構新增至 iOS (Swift) 應用程式

MSAL 驗證 SDK 可用來使用標準 OAuth2 和 OpenID Connect 將驗證整合到您的應用程式中。 它可讓您使用Microsoft身分識別來登入使用者或應用程式。 若要將 MSAL 新增至 iOS (Swift) 專案,請遵循下列步驟:

  1. 在 Xcode 中開啟您的 iOS 專案。
  2. 從 [檔案] 功能選取 [[新增套件相依性...]
  3. 輸入 https://github.com/AzureAD/microsoft-authentication-library-for-objc 作為套件 URL,然後選擇 [新增套件

更新套件組合標識碼

在 Apple 生態系統中,套件組合識別碼是應用程式的唯一標識碼。 若要更新專案中的套件組合識別碼,請遵循下列步驟:

  1. 開啟項目設定。 在 [身分識別] 區段中,輸入 套件組合標識碼

  2. 右鍵點擊 Info.plist,然後選取 開啟為>原始程式碼

  3. 在字典根節點底下,將 Enter_the_bundle_Id_Here 取代為您在入口網站中使用的 Bundle Id。 請注意字串中的 msauth. 前置詞。

    <key>CFBundleURLTypes</key>
    <array>
       <dict>
          <key>CFBundleURLSchemes</key>
          <array>
             <string>msauth.Enter_the_Bundle_Id_Here</string>
          </array>
       </dict>
    </array>
    

建立 SDK 實例

若要在專案中建立 MSAL 實例,請遵循下列步驟:

  1. 將 MSAL 程式庫導入到您的視圖控制器中,方法是將 import MSAL 新增到 ViewController 類別的頂部。

  2. applicationContext 成員變數新增至 ViewController 類別,方法是在 viewDidLoad() 函式之前新增下列程式代碼:

    var applicationContext : MSALPublicClientApplication?
    var webViewParameters : MSALWebviewParameters?
    

    程式代碼會宣告兩個變數:applicationContext,其會儲存 MSALPublicClientApplication的實例,以及儲存 MSALWebviewParameters實例的 webViewParametersMSALPublicClientApplication 是由 MSAL 提供的類別,用於處理公用用戶端應用程式。 MSALWebviewParameters 是由 MSAL 提供的類別,定義在驗證程式期間用來設定 Web 檢視的參數。

  3. 將下列程式代碼新增至檢視 viewDidLoad() 函式:

     do {
            try self.initMSAL()
        } catch let error {
            self.updateLogging(text: "Unable to create Application Context \(error)")
        }
    

    程式代碼會嘗試初始化 MSAL,處理進程期間發生的任何錯誤。 如果發生錯誤,系統會將錯誤詳細資料記錄到日誌中。

  4. 新增下列程序代碼,以建立 initMSAL() 函式,以初始化 MSAL:

        func initMSAL() throws {
    
        guard let authorityURL = URL(string: Configuration.kAuthority) else {
            self.updateLogging(text: "Unable to create authority URL")
            return
        }
    
        let authority = try MSALCIAMAuthority(url: authorityURL)
    
        let msalConfiguration = MSALPublicClientApplicationConfig(clientId: Configuration.kClientID,
                                                                  redirectUri: Configuration.kRedirectUri,
                                                                  authority: authority)
        self.applicationContext = try MSALPublicClientApplication(configuration: msalConfiguration)
    }
    

    此程式代碼會初始化 iOS 的 MSAL。 它會先嘗試使用提供的 Configuration.kAuthority 字串來建立授權單位的 URL。 如果成功,它會根據該 URL 建立 MSAL 授權單位物件。 然後,它會使用指定的客戶端 ID、重新導向 URI 和授權機構來設定 MSALPublicClientApplication。 如果已正確設定所有組態,它會使用已設定的 MSALPublicClientApplication初始化應用程式內容。 如果過程中發生任何錯誤,則會拋出錯誤。

  5. 建立 Configuration.swift 檔案,並新增下列設定:

    import Foundation
    
    @objcMembers
    class Configuration {
        static let kTenantSubdomain = "Enter_the_Tenant_Subdomain_Here"
    
        // Update the below to your client ID you received in the portal.
        static let kClientID = "Enter_the_Application_Id_Here"
        static let kRedirectUri = "Enter_the_Redirect_URI_Here"
        static let kProtectedAPIEndpoint = "Enter_the_Protected_API_Full_URL_Here"
        static let kScopes = ["Enter_the_Protected_API_Scopes_Here"]
    
        static let kAuthority = "https://\(kTenantSubdomain).ciamlogin.com"
    
    }
    

    此 Swift 組態程式代碼會定義名為 Configuration 的類別,並以 @objcMembers標示。 它包含與驗證設定相關的各種組態參數的靜態常數。 這些參數包括 租使用者子域用戶端標識子重新導向 URI受保護的 API 端點,以及 範圍。 這些組態常數應該使用應用程式設定特有的適當值來更新。

    尋找佔位符:

    • Enter_the_Application_Id_Here,然後用您稍早註冊的應用程式的 應用程式(用戶端)ID 取代它。
    • Enter_the_Redirect_URI_Here,並用您稍早在新增平臺重新導向 URL 時下載的 MSAL 組態檔中的 kRedirectUri 值取代它。
    • Enter_the_Protected_API_Scopes_Here,並將它替換為稍早記錄的作用域。 如果您尚未記錄任何範圍,您可以將此範圍清單保留空白。
    • Enter_the_Tenant_Subdomain_Here,並將它取代為 Directory (tenant) 子域。 例如,如果您的租戶的主要網域是 contoso.onmicrosoft.com,請使用 contoso。 如果您不知道租戶子域,請瞭解如何 閱讀租戶詳細資訊

使用自訂網址 (選擇性)

使用自訂網域來全面品牌化驗證 URL。 從用戶的觀點來看,用戶在驗證程序期間會留在您的網域上,而不是重新導向至 ciamlogin.com 網域名稱。

使用下列步驟來使用自訂網域:

  1. 使用 的步驟在外部租用戶的應用程式中啟用自定義 URL 網域,然後使用 為外部租用戶啟用自定義 URL 網域。

  2. 開啟 Configuration.swift 檔案:

    1. kAuthority 屬性的值更新為 https://Enter_the_Custom_Domain_Here/Enter_the_Tenant_ID_Here。 將 Enter_the_Custom_Domain_Here 取代為您的自定義 URL 網域,並以您的租使用者標識碼 Enter_the_Tenant_ID_Here。 如果您沒有租戶 ID,請瞭解如何 查看租戶詳細資料

Configuration.swift 檔案進行變更之後,如果您的自定義 URL 網域是 login.contoso.com,且您的租使用者識別碼是 aaaabbbb-0000-cccc-1111-dddd2222eeee,那麼您的檔案應該如下列代碼段所示:

    import Foundation

    @objcMembers
    class Configuration {
        static let kTenantSubdomain = "login.contoso.com"
        
        // Update the below to your client ID you received in the portal.
        static let kClientID = "Enter_the_Application_Id_Here"
        static let kRedirectUri = "Enter_the_Redirect_URI_Here"
        static let kProtectedAPIEndpoint = "Enter_the_Protected_API_Full_URL_Here"
        static let kScopes = ["Enter_the_Protected_API_Scopes_Here"]
        
        static let kAuthority = "https://\(kTenantSubdomain)/aaaabbbb-0000-cccc-1111-dddd2222eeee"
    
    }

後續步驟