在 Apple 平台上使用 Microsoft 進行驗證

您可以讓使用者使用 OAuth 供應商通過 Firebase 驗證,例如 整合網頁式一般 OAuth 登入機制的 Microsoft Azure Active Directory 進入您的應用程式,並透過 Firebase SDK 執行端對端登入流程。

事前準備

使用 Microsoft 帳戶 (Azure Active Directory 和個人) 登入使用者 Microsoft 帳戶),您必須先將 Microsoft 設為 來建立 Firebase 專案:

  1. 將 Firebase 新增至 Apple 專案
  2. Firebase 控制台中開啟「Auth」專區。
  3. 在「Sign in method」分頁中,啟用「Microsoft」供應商。
  4. 將供應商開發人員主控台中的「用戶端 ID」和「用戶端密鑰」新增至 提供者設定:
    1. 如要註冊 Microsoft OAuth 用戶端,請按照 快速入門導覽課程:使用 Azure Active Directory v2.0 端點註冊應用程式。 請注意,這個端點支援使用 Microsoft 個人帳戶和 Azure 登入 Active Directory 帳戶。 瞭解詳情 Azure Active Directory v2.0 的相關資訊。
    2. 向這些供應商註冊應用程式時,請務必註冊 專案的 *.firebaseapp.com 網域,做為專案的重新導向網域 應用程式。
  5. 按一下 [儲存]

使用 Firebase SDK 處理登入流程

如要使用 Firebase Apple 平台 SDK 處理登入流程,請按照下列步驟操作:

  1. 在 Xcode 專案中新增自訂網址配置:

    1. 開啟專案設定:按兩下 左側樹狀檢視中從「目標」部分中選取應用程式,然後 選取「資訊」分頁標籤,然後展開「網址類型」部分。
    2. 點選「+」按鈕,然後將經過編碼的應用程式 ID 新增為網址 配置。如要找到經過編碼的應用程式 ID,請前往 一般 Firebase 控制台的「設定」頁面,位於 iOS 裝置的專區 應用程式。將其他欄位留白。

      設定完成後,設定看起來應該會與 後面 (但採用您應用程式的專屬值):

      Xcode 自訂網址配置設定介面的螢幕擷取畫面
  2. 使用提供者 ID 建立 OAuthProvider 執行個體 microsoft.com

    SwiftObjective-C
        var provider = OAuthProvider(providerID: "microsoft.com")
        
        FIROAuthProvider *provider = [FIROAuthProvider providerWithProviderID:@"microsoft.com"];
        
  3. 選用:指定您想要的其他自訂 OAuth 參數。 與 OAuth 要求一起傳送

    SwiftObjective-C
        provider.customParameters = [
          "prompt": "consent",
          "login_hint": "user@firstadd.onmicrosoft.com"
        ]
        
        [provider setCustomParameters:@{@"prompt": @"consent", @"login_hint": @"user@firstadd.onmicrosoft.com"}];
        

    如需 Microsoft 支援的參數,請參閱 Microsoft OAuth 說明文件。 請注意,您無法透過 setCustomParameters。這些參數都是 client_id response_typeredirect_uristatescoperesponse_mode

    只允許特定 Azure AD 用戶群的使用者簽署 插入應用程式,即 Azure AD 用戶群的易記網域名稱 可以使用用戶群 GUID ID。方法是指定 「用戶群」欄位的值。

    SwiftObjective-C
        provider.customParameters = [
          // Optional "tenant" parameter in case you are using an Azure AD
          // tenant. eg. '8eaef023-2b34-4da1-9baa-8bc8c9d6a490' or
          // 'contoso.onmicrosoft.com' or "common" for tenant-independent
          // tokens. The default value is "common".
          "tenant": "TENANT_ID"
        ]
        
        // Optional "tenant" parameter in case you are using an Azure AD tenant.
        // eg. '8eaef023-2b34-4da1-9baa-8bc8c9d6a490' or
        // 'contoso.onmicrosoft.com' or "common" for tenant-independent tokens.
        // The default value is "common".
        provider.customParameters = @{@"tenant": @"TENANT_ID"};
        
  4. 選用:指定基本設定檔以外的其他 OAuth 2.0 範圍, 設為要向驗證服務供應商發出要求

    SwiftObjective-C
        provider.scopes = ["mail.read", "calendars.read"]
        
        [provider setScopes:@[@"mail.read", @"calendars.read"]];
        

    詳情請參閱 Microsoft 權限和同意聲明說明文件

  5. 選用:如要自訂應用程式的呈現方式 SFSafariViewControllerUIWebView 符合以下條件時 向使用者顯示 reCAPTCHA 或是建立 並傳遞至 AuthUIDelegate 通訊協定 credentialWithUIDelegate

  6. 使用 OAuth 提供者物件向 Firebase 進行驗證。

    SwiftObjective-C
        // Replace nil with the custom class that conforms to AuthUIDelegate
        // you created in last step to use a customized web view.
        provider.getCredentialWith(nil) { credential, error in
          if error != nil {
            // Handle error.
          }
          if credential != nil {
            Auth().signIn(with: credential) { authResult, error in
              if error != nil {
                // Handle error.
              }
              // User is signed in.
              // IdP data available in authResult.additionalUserInfo.profile.
              // OAuth access token can also be retrieved:
              // (authResult.credential as? OAuthCredential)?.accessToken
              // OAuth ID token can also be retrieved:
              // (authResult.credential as? OAuthCredential)?.idToken
            }
          }
        }
        
        [provider getCredentialWithUIDelegate:nil
                                   completion:^(FIRAuthCredential *_Nullable credential, NSError *_Nullable error) {
          if (error) {
           // Handle error.
          }
          if (credential) {
            [[FIRAuth auth] signInWithCredential:credential
                                      completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
              if (error) {
                // Handle error.
              }
              // User is signed in.
              // IdP data available in authResult.additionalUserInfo.profile.
              // OAuth access token can also be retrieved:
              // ((FIROAuthCredential *)authResult.credential).accessToken
              // OAuth ID token can also be retrieved:
              // ((FIROAuthCredential *)authResult.credential).idToken
            }];
          }
        }];
        

    使用 OAuth 存取權杖可讓您呼叫 Microsoft Graph API

    例如,如要取得基本個人資料資訊 您可以呼叫 REST API 透過 Authorization 標頭傳遞存取權杖:

    https://graph.microsoft.com/v1.0/me

    有別於 Firebase Auth 支援的其他供應商,Microsoft 不需要 提供相片網址,並改為個人資料相片的二進位資料 透過以下方式要求: Microsoft Graph API

    除了 OAuth 存取權杖外,使用者的 OAuth ID 權杖 您也可從 OAuthCredential 物件擷取。 ID 權杖中的 sub 憑證附加資訊僅適用於應用程式,且與聯合值不相符 Firebase 驗證所使用的使用者 ID,可透過 user.providerData[0].uid。請改用 oid 憑證欄位。 使用 Azure AD 用戶群登入時,oid 憑證附加資訊會完全相同 比對。 但如果是非用戶群的情況,系統會填補 oid 欄位。聯合 ID 4b2eabcdefghijkloid 會有表單 00000000-0000-0000-4b2e-abcdefghijkl

  7. 以上範例著重登入流程,不過您可以 能讓您使用 linkWithCredential。舉例來說 以便將兩者登入

    SwiftObjective-C
        Auth().currentUser.link(withCredential: credential) { authResult, error in
          if error != nil {
            // Handle error.
          }
          // Microsoft credential is linked to the current user.
          // IdP data available in authResult.additionalUserInfo.profile.
          // OAuth access token can also be retrieved:
          // (authResult.credential as? OAuthCredential)?.accessToken
          // OAuth ID token can also be retrieved:
          // (authResult.credential as? OAuthCredential)?.idToken
        }
        
        [[FIRAuth auth].currentUser
            linkWithCredential:credential
                    completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
          if (error) {
            // Handle error.
          }
          // Microsoft credential is linked to the current user.
          // IdP data available in authResult.additionalUserInfo.profile.
          // OAuth access token can also be retrieved:
          // ((FIROAuthCredential *)authResult.credential).accessToken
          // OAuth ID token can also be retrieved:
          // ((FIROAuthCredential *)authResult.credential).idToken
        }];
        
  8. 相同的模式 reauthenticateWithCredential,可用於 為需要近期執行的敏感作業擷取新憑證 登入。

    SwiftObjective-C
        Auth().currentUser.reauthenticateWithCredential(withCredential: credential) { authResult, error in
          if error != nil {
            // Handle error.
          }
          // User is re-authenticated with fresh tokens minted and
          // should be able to perform sensitive operations like account
          // deletion and email or password update.
          // IdP data available in result.additionalUserInfo.profile.
          // Additional OAuth access token can also be retrieved:
          // (authResult.credential as? OAuthCredential)?.accessToken
          // OAuth ID token can also be retrieved:
          // (authResult.credential as? OAuthCredential)?.idToken
        }
        
        [[FIRAuth auth].currentUser
            reauthenticateWithCredential:credential
                              completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
          if (error) {
            // Handle error.
          }
          // User is re-authenticated with fresh tokens minted and
          // should be able to perform sensitive operations like account
          // deletion and email or password update.
          // IdP data available in result.additionalUserInfo.profile.
          // Additional OAuth access token can also be retrieved:
          // ((FIROAuthCredential *)authResult.credential).accessToken
          // OAuth ID token can also be retrieved:
          // ((FIROAuthCredential *)authResult.credential).idToken
        }];
        

如果您已在 Firebase 控制台中啟用「每個電子郵件地址一個帳戶」設定: 使用者嘗試使用現有的電子郵件地址登入供應商 (例如 Microsoft) 時 也存在於其他 Firebase 使用者的供應商 (例如 Google) 中,因此發生錯誤 FIRAuthErrorCodeAccountExistsWithDifferentCredential 會與臨時暫存檔一起擲回 FIRAuthCredential 物件 (Microsoft 憑證)。如要完成 使用者必須先登入現有的供應商 (Google),才能連結至 先前的 FIRAuthCredential (Microsoft 憑證)。如下所示:

SwiftObjective-C
  // Sign-in with an OAuth credential.
  provider.getCredentialWith(nil) { credential, error in
    // An account with the same email already exists.
    if (error as NSError?)?.code == AuthErrorCode.accountExistsWithDifferentCredential.rawValue {
      // Get pending credential and email of existing account.
      let existingAcctEmail = (error! as NSError).userInfo[AuthErrorUserInfoEmailKey] as! String
      let pendingCred = (error! as NSError).userInfo[AuthErrorUserInfoUpdatedCredentialKey] as! AuthCredential
      // Lookup existing account identifier by the email.
      Auth.auth().fetchProviders(forEmail:existingAcctEmail) { providers, error in
        // Existing email/password account.
        if (providers?.contains(EmailAuthProviderID))! {
          // Existing password account for email. Ask user to provide the password of the
          // existing account.
          // Sign in with existing account.
          Auth.auth().signIn(withEmail:existingAcctEmail, password:password) { user, error in
            // Successfully signed in.
            if user != nil {
              // Link pending credential to account.
              Auth.auth().currentUser?.linkAndRetrieveData(with: pendingCred) { result, error in
                // ...
              }
            }
          }
        }
      }
      return
    }

    // Other errors.
    if error != nil {
      // handle the error.
      return
    }

    // Sign in with the credential.
    if credential != nil {
      Auth.auth().signInAndRetrieveData(with: credential!) { result, error in
        if error != nil {
          // handle the error.
          return
        }
      }
    }
  }

  
  // Sign-in with an OAuth credential.
  [provider getCredentialWithUIDelegate:nil
                             completion:^(FIRAuthCredential *_Nullable credential, NSError *_Nullable error) {
    // An account with the same email already exists.
    if (error.code == FIRAuthErrorCodeAccountExistsWithDifferentCredential) {
      // Get pending credential and email of existing account.
      NSString *existingAcctEmail = error.userInfo[FIRAuthErrorUserInfoEmailKey];
      FIRAuthCredential *pendingCred = error.userInfo[FIRAuthErrorUserInfoUpdatedCredentialKey];
      // Lookup existing account identifier by the email.
      [[FIRAuth auth] fetchProvidersForEmail:existingAcctEmail
                                 completion:^(NSArray<NSString *> *_Nullable providers,
                                              NSError *_Nullable error) {
        // Existing email/password account.
        if ( [providers containsObject:FIREmailAuthProviderID] ) {
          // Existing password account for email. Ask user to provide the password of the
          // existing account.

          // Sign in with existing account.
          [[FIRAuth auth] signInWithEmail:existingAcctEmail
                                 password:password
                               completion:^(FIRUser *user, NSError *error) {
            // Successfully signed in.
            if (user) {
              // Link pending credential to account.
              [[FIRAuth auth].currentUser linkWithCredential:pendingCred
                                                  completion:^(FIRUser *_Nullable user,
                                                               NSError *_Nullable error) {
                // ...
              }];
            }
          }];
        }
      }];
      return;
    }

    // Other errors.
    if (error) {
      // handle the error.
      return;
    }

    // Sign in with the credential.
    if (credential) {
      [[FIRAuth auth] signInAndRetrieveDataWithCredential:credential
          completion:^(FIRAuthDataResult *_Nullable authResult,
                       NSError *_Nullable error) {
        if (error) {
          // handle the error.
          return;
        }
      }];
    }
  }];
  

不同於 Firebase 支援的其他 OAuth 供應商,例如 Google、Facebook 和 Twitter,使用 OAuth 存取權杖直接登入 基於這個原因,Firebase Auth 不支援 這是因為 Firebase 無法使用 驗證伺服器,用於驗證 Microsoft OAuth 存取權杖的目標對象。 這是重大的安全需求,可能會公開應用程式和 會導致網站重新發動攻擊,攻擊者必須取得 Microsoft OAuth 存取權杖 一個專案 (攻擊者) 可用來登入另一個專案 (受害者)。 而是讓 Firebase 驗證能夠處理整個 OAuth 流程, 使用 OAuth 用戶端 ID 和密鑰進行授權碼交換 就可在 Firebase 控制台設定因為授權碼 搭配特定的用戶端 ID/密鑰 (授權碼) 每項專案取得的 均無法與另一項專案搭配使用

如果必須在不支援的環境中使用這些提供者, 第三方 OAuth 程式庫 Firebase 自訂驗證 。需要前者才能向供應商進行驗證 和後者,用於交換提供者憑證供自訂權杖使用。

使用者首次登入後,系統會建立新的使用者帳戶 也就是使用者的名稱和密碼 號碼或驗證提供者資訊,也就是使用者登入時使用的網址。這項新功能 帳戶儲存為 Firebase 專案的一部分,可用來識別 即可限制使用者登入專案中的所有應用程式

  • 在您的應用程式中,您可以透過 User 物件。請參閱管理使用者

  • 在你的Firebase Realtime DatabaseCloud Storage中 查看安全性規則 透過 auth 變數取得已登入使用者的不重複使用者 ID。 控管使用者可以存取的資料

您可以讓使用者透過多重驗證機制登入您的應用程式 將驗證供應商憑證連結至 現有的使用者帳戶

如要登出使用者,請呼叫 signOut:

SwiftObjective-C
let firebaseAuth = Auth.auth()
do {
  try firebaseAuth.signOut()
} catch let signOutError as NSError {
  print("Error signing out: %@", signOutError)
}
NSError *signOutError;
BOOL status = [[FIRAuth auth] signOut:&signOutError];
if (!status) {
  NSLog(@"Error signing out: %@", signOutError);
  return;
}

我們也建議您新增錯誤處理程式碼,適用於完整的驗證範圍 發生錯誤。請參閱處理錯誤