Catch up on highlights from Firebase at Google I/O 2023. Learn more

在 Apple 平台上使用 Twitter 進行身份驗證

您可以使用 Firebase SDK 將通用 OAuth 登錄集成到您的應用程序中,以執行端到端登錄流程,讓您的用戶使用 Twitter 等 OAuth 提供商通過 Firebase 進行身份驗證。

在你開始之前

使用 Swift Package Manager 安裝和管理 Firebase 依賴項。

  1. 在 Xcode 中,打開應用程序項目,導航至File > Add Packages
  2. 出現提示時,添加 Firebase Apple 平台 SDK 存儲庫:
  3.   https://github.com/firebase/firebase-ios-sdk
  4. 選擇 Firebase 身份驗證庫。
  5. 完成後,Xcode 將自動開始在後台解析並下載您的依賴項。

要使用 Twitter 帳戶登錄用戶,您必須首先啟用 Twitter 作為 Firebase 項目的登錄提供商:

  1. 將 Firebase 添加到您的 Apple 項目

  2. Podfile中包含以下 pod:

    pod 'FirebaseAuth'
    
  3. Firebase 控制台中,打開“身份驗證”部分。
  4. “登錄方法”選項卡上,啟用Twitter提供程序。
  5. 將該提供商的開發者控制台中的API 密鑰API 密鑰添加到提供商配置中:
    1. 在 Twitter 上將您的應用程序註冊為開發人員應用程序,並獲取您的應用程序的 OAuth API keyAPI Secret
    2. 確保您的 Firebase OAuth 重定向 URI (例如my-app-12345.firebaseapp.com/__/auth/handler )在Twitter 應用的 config上的應用設置頁面中設置為授權回調 URL
  6. 單擊“保存”

使用 Firebase SDK 處理登錄流程

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

  1. 將自定義 URL 方案添加到您的 Xcode 項目:

    1. 打開項目配置:雙擊左側樹視圖中的項目名稱。從“目標”部分選擇您的應用程序,然後選擇“信息”選項卡,並展開“URL 類型”部分。
    2. 單擊+按鈕,並將您的編碼應用程序 ID 添加為 URL 方案。您可以在 Firebase 控制台的“常規設置”頁面上的 iOS 應用部分中找到您的編碼應用 ID。將其他字段留空。

      完成後,您的配置應類似於以下內容(但具有特定於應用程序的值):

      Xcode的自定義URL方案設置界面截圖

  2. 使用提供者 ID twitter.com創建OAuthProvider的實例。

    迅速

        var provider = OAuthProvider(providerID: "twitter.com")
        

    Objective-C

        FIROAuthProvider *provider = [FIROAuthProvider providerWithProviderID:@"twitter.com"];
        
  3. 可選:指定要與 OAuth 請求一起發送的其他自定義 OAuth 參數。

    迅速

        provider.customParameters = [
          "lang": "fr"
          ]
        

    Objective-C

        [provider setCustomParameters:@{@"lang": @"fr"}];
        

    有關 Twitter 支持的參數,請參閱Twitter OAuth 文檔。請注意,您無法使用setCustomParameters傳遞 Firebase 所需的參數。這些參數是client_idredirect_uriresponse_typescopestate

  4. 可選:如果要自定義應用程序在向用戶顯示 reCAPTCHA 時呈現SFSafariViewControllerUIWebView的方式,請創建一個符合AuthUIDelegate協議的自定義類,並將其傳遞給credentialWithUIDelegate

  5. 使用 OAuth 提供程序對象通過 Firebase 進行身份驗證。

    迅速

        provider.getCredentialWith(nil) { credential, error in
          if error != nil {
            // Handle error.
          }
          if credential != nil {
            Auth.auth().signIn(with: credential) { authResult, error in
              if error != nil {
                // Handle error.
              }
              // User is signed in.
              // IdP data available in authResult.additionalUserInfo.profile.
              // Twitter OAuth access token can also be retrieved by:
              // (authResult.credential as? OAuthCredential)?.accessToken
              // Twitter OAuth ID token can be retrieved by calling:
              // (authResult.credential as? OAuthCredential)?.idToken
              // Twitter OAuth secret can be retrieved by calling:
              // (authResult.credential as? OAuthCredential)?.secret
            }
          }
        }
        

    Objective-C

        [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.
              // Twitter OAuth access token can also be retrieved by:
              // authResult.credential.accessToken
              // Twitter OAuth ID token can be retrieved by calling:
              // authResult.credential.idToken
              // Twitter OAuth secret can be retrieved by calling:
              // authResult.credential.secret
            }];
          }
        }];
        

    使用 OAuth 訪問令牌,您可以調用Twitter API

    例如,要獲取基本配置文件信息,您可以調用 REST API,在Authorization標頭中傳遞訪問令牌:

    https://api.twitter.com/labs/1/users?usernames=TwitterDev
    
  6. 雖然上述示例重點關注登錄流程,但您還可以將 Twitter 提供商鏈接到現有用戶。例如,您可以將多個提供商鏈接到同一用戶,允許他們使用其中任一提供商登錄。

    迅速

        Auth().currentUser.link(withCredential: credential) { authResult, error in
          if error != nil {
            // Handle error.
          }
          // Twitter credential is linked to the current user.
          // IdP data available in authResult.additionalUserInfo.profile.
          // Twitter OAuth access token can also be retrieved by:
          // (authResult.credential as? OAuthCredential)?.accessToken
          // Twitter OAuth ID token can be retrieved by calling:
          // (authResult.credential as? OAuthCredential)?.idToken
          // Twitter OAuth secret can be retrieved by calling:
          // (authResult.credential as? OAuthCredential)?.secret
        }
        

    Objective-C

        [[FIRAuth auth].currentUser
            linkWithCredential:credential
                    completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
          if (error) {
            // Handle error.
          }
          // Twitter credential is linked to the current user.
          // IdP data available in authResult.additionalUserInfo.profile.
          // Twitter OAuth access token is can also be retrieved by:
          // ((FIROAuthCredential *)authResult.credential).accessToken
          // Twitter OAuth ID token can be retrieved by calling:
          // ((FIROAuthCredential *)authResult.credential).idToken
          // Twitter OAuth secret can be retrieved by calling:
          // ((FIROAuthCredential *)authResult.credential).secret
        }];
        
  7. 相同的模式可以與reauthenticateWithCredential一起使用,它可用於檢索需要最近登錄的敏感操作的新憑據。

    迅速

        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 is can also be retrieved by:
          // (authResult.credential as? OAuthCredential)?.accessToken
          // Twitter OAuth ID token can be retrieved by calling:
          // (authResult.credential as? OAuthCredential)?.idToken
          // Twitter OAuth secret can be retrieved by calling:
          // (authResult.credential as? OAuthCredential)?.secret
        }
        

    Objective-C

        [[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 is can also be retrieved by:
          // ((FIROAuthCredential *)authResult.credential).accessToken
          // Twitter OAuth ID token can be retrieved by calling:
          // ((FIROAuthCredential *)authResult.credential).idToken
          // Twitter OAuth secret can be retrieved by calling:
          // ((FIROAuthCredential *)authResult.credential).secret
        }];
        

下一步

用戶首次登錄後,系統會創建一個新的用戶帳戶,並將其鏈接到用戶登錄時使用的憑據(即用戶名和密碼、電話號碼或身份驗證提供商信息)。此新帳戶將作為 Firebase 項目的一部分存儲,並且可用於識別項目中每個應用中的用戶,無論用戶如何登錄。

  • 在您的應用程序中,您可以從User對象獲取用戶的基本個人資料信息。請參閱管理用戶

  • 在 Firebase 實時數據庫和雲存儲安全規則中,您可以從auth變量獲取登錄用戶的唯一用戶 ID,並使用它來控制用戶可以訪問哪些數據。

您可以通過將身份驗證提供程序憑據鏈接到現有用戶帳戶,允許用戶使用多個身份驗證提供程序登錄您的應用程序。

要註銷用戶,請調用signOut:

迅速

let firebaseAuth = Auth.auth()
do {
  try firebaseAuth.signOut()
} catch let signOutError as NSError {
  print("Error signing out: %@", signOutError)
}

Objective-C

NSError *signOutError;
BOOL status = [[FIRAuth auth] signOut:&signOutError];
if (!status) {
  NSLog(@"Error signing out: %@", signOutError);
  return;
}

您可能還需要為所有身份驗證錯誤添加錯誤處理代碼。請參閱處理錯誤