在 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.git
  4. 選擇 Firebase Authentication 程式庫。
  5. -ObjC 標記新增至目標的建構設定「Other Linker Flags」部分。
  6. 完成後,Xcode 就會自動開始在背景中解析並下載依附元件。

如要使用 Twitter 帳戶登入使用者,您必須先將 Twitter 設為 Firebase 專案的登入服務供應商:

  1. 將 Firebase 新增至 Apple 專案

  2. 請在 Podfile 中加入下列 Pod:

    pod 'FirebaseAuth'
  3. Firebase 控制台中,開啟「Auth」部分。
  4. 在「登入方式」分頁中,啟用「Twitter」供應器。
  5. 將該供應商的開發人員控制台中的 API 金鑰API 密鑰新增至供應商設定:
    1. 將應用程式註冊為 Twitter 上的開發人員應用程式,並取得應用程式的 OAuth API 金鑰API 密鑰
    2. 請確認 Twitter 應用程式設定中的 Firebase OAuth 重新導向網址 (例如 my-app-12345.firebaseapp.com/__/auth/handler) 已設為應用程式設定頁面中的授權回呼網址
  6. 按一下 [儲存]

使用 Firebase SDK 處理登入流程

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

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

    1. 開啟專案設定:在左側樹狀檢視畫面中,按兩下專案名稱。從「TARGETS」部分選取應用程式,然後選取「Info」分頁標籤,並展開「URL Types」部分。
    2. 按一下「+」按鈕,然後將已編碼的應用程式 ID 新增為網址配置。您可以在 Firebase 控制台的「General Settings」頁面中,找到 iOS 應用程式的「Encoded App ID」部分。請將其他欄位留空。

      完成後,設定應類似於下列內容 (但會顯示應用程式專屬的值):

      Xcode 自訂網址配置介面的螢幕截圖

  2. 使用提供者 ID twitter.com 建立 OAuthProvider 例項。

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

    SwiftObjective-C
        provider.customParameters = [
          "lang": "fr"
          ]
        
        [provider setCustomParameters:@{@"lang": @"fr"}];
        

    如要瞭解 Twitter 支援的參數,請參閱 Twitter OAuth 說明文件。請注意,您無法使用 setCustomParameters 傳遞 Firebase 必要參數。這些參數包括 client_idredirect_uriresponse_typescopestate

  4. 選用:如果您想自訂應用程式向使用者顯示 reCAPTCHA 時,呈現 SFSafariViewControllerUIWebView 的方式,請建立符合 AuthUIDelegate 通訊協定的自訂類別,並將其傳遞至 credentialWithUIDelegate

  5. 使用 OAuth 提供者物件,透過 Firebase 進行驗證。

    SwiftObjective-C
        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
            }
          }
        }
        
        [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 供應商連結至現有使用者。舉例來說,您可以將多個提供者連結至同一位使用者,讓他們使用任一提供者登入。

    SwiftObjective-C
        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
        }
        
        [[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 可用於擷取敏感作業的最新憑證,而這類作業需要最近登入。因此,您可以使用相同的模式搭配 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 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
        }
        
        [[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 主控台中啟用「每個電子郵件地址只能建立一個帳戶」設定,當使用者嘗試使用另一個 Firebase 使用者供應商 (例如 Google) 的電子郵件地址登入供應商 (例如 Twitter) 時,系統會擲回錯誤 FIRAuthErrorCodeAccountExistsWithDifferentCredential,並附上暫時的 FIRAuthCredential 物件 (Twitter 憑證)。如要完成登入指定提供者的程序,使用者必須先登入現有提供者 (Google),然後連結至前述的 FIRAuthCredential (Twitter 憑證)。如下所示:

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 專案中,無論使用者如何登入,都可以用於在專案中的每個應用程式中識別使用者。

  • 在應用程式中,您可以從 User 物件取得使用者的個人資料基本資訊。請參閱「管理使用者」。

  • Firebase Realtime DatabaseCloud Storage 安全性規則中,您可以從 auth 變數取得已登入使用者的專屬使用者 ID,並利用該 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;
}

您可能還想為各種驗證錯誤新增錯誤處理程式碼。請參閱「處理錯誤」。