在 Apple 平台上透過 Twitter 進行驗證

您可以使用 Firebase SDK 將一般 OAuth 登入整合至您的應用程式,讓使用者透過 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 驗證資料庫。
  5. 在目標建構設定的「Other Linker Flags」部分中新增 -ObjC 標記。
  6. 完成後,Xcode 會自動開始在背景解析並下載依附元件。

如要使用 Twitter 帳戶登入使用者,您必須先啟用 Twitter 做為 Firebase 專案的登入提供者:

  1. 將 Firebase 新增至 Apple 專案

  2. Podfile 中加入下列 Pod:

    pod 'FirebaseAuth'
    

  3. Firebase 控制台開啟「驗證」專區。
  4. 在「Sign in method」分頁中,啟用 Twitter 供應商。
  5. 將供應商開發人員主控台中的 API 金鑰API 密鑰新增至供應商設定:
    1. 在 Twitter 上將應用程式註冊為開發人員應用程式,並取得應用程式的 OAuth API 金鑰API 密鑰
    2. 前往 Twitter 應用程式設定的應用程式設定頁面,確認 Firebase OAuth 重新導向 URI (例如 my-app-12345.firebaseapp.com/__/auth/handler) 已設為「授權回呼網址」
  6. 點選「Save」

使用 Firebase SDK 處理登入流程

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

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

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

      設定完成後,設定看起來應類似下列內容 (但會使用您的應用程式專屬值):

      Xcode 自訂網址配置設定介面的螢幕擷取畫面

  2. 使用供應商 ID twitter.com 建立 OAuthProvider 的執行個體。

    Swift

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

    Objective-C

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

    Swift

        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 進行驗證。

    Swift

        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 供應商連結至現有使用者。例如,您可以將多個供應商連結至同一位使用者,讓對方透過任一提供者登入。

    Swift

        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 搭配使用,以針對需要近期登入的敏感作業擷取新憑證。

    Swift

        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 即時資料庫和 Cloud Storage 安全性規則中,您可以透過 auth 變數取得登入使用者的專屬 ID,並使用該 ID 控管使用者可存取哪些資料。

您可以將驗證供應商憑證連結至現有的使用者帳戶,讓使用者透過多個驗證服務提供者登入您的應用程式。

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

Swift

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;
}

您可能也想要針對各種驗證錯誤加入錯誤處理程式碼。請參閱處理錯誤