在 Apple 平台上以匿名方式透過 Firebase 驗證

您可以使用 Firebase Authentication 建立及使用臨時匿名帳戶,向 Firebase 驗證身分。這些臨時匿名帳戶可讓尚未註冊應用程式的使用者,使用受安全性規則保護的資料。如果匿名使用者決定註冊應用程式,您可以將他們的登入憑證連結至匿名帳戶,這樣他們就能在日後的作業階段中繼續使用受保護的資料。

事前準備

  1. 使用 Swift Package Manager 安裝及管理 Firebase 依附元件。

    1. 在 Xcode 中保持開啟應用程式專案,然後依序點選「File」(檔案) 和「Add Packages」(新增 Package)。
    2. 系統提示時,請新增 Firebase Apple 平台 SDK 存放區:
    3.   https://github.com/firebase/firebase-ios-sdk.git
    4. 選擇 Firebase Authentication 程式庫。
    5. 在目標建構設定的「Other Linker Flags」部分,新增 -ObjC 標記。
    6. 完成後,Xcode 會自動開始在背景解析及下載依附元件。
  2. 如果尚未將應用程式連結至 Firebase 專案,請前往 Firebase 控制台進行連結。
  3. 啟用匿名驗證:
    1. 在 Firebase 控制台中,依序前往 「Security」(安全性) >「Authentication」(驗證)。
    2. 在「登入方式」分頁中,啟用「匿名」登入供應商。
    3. 選用:如果已將專案升級至 Firebase Authentication with Identity Platform,可以啟用自動清理功能。啟用這項設定後,系統會自動刪除建立超過 30 天的匿名帳戶。在啟用自動清理功能的專案中,匿名驗證將不再計入用量限制或計費配額。請參閱「自動清理」。

以匿名方式向 Firebase 驗證

如果未登入的使用者要使用需要 Firebase 驗證的應用程式功能,請完成下列步驟,讓使用者以匿名方式登入:

  1. 在 UIApplicationDelegate 中匯入 FirebaseCore 模組,以及應用程式委派使用的任何其他 Firebase 模組。舉例來說,如要使用 Cloud Firestore 和 Authentication:

    SwiftUI

    import SwiftUI
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    Swift

    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    Objective-C

    @import FirebaseCore;
    @import FirebaseFirestore;
    @import FirebaseAuth;
    // ...
          
  2. 在應用程式委派的 application(_:didFinishLaunchingWithOptions:) 方法中,設定 FirebaseApp 共用例項:

    SwiftUI

    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    Swift

    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
  3. 如果您使用 SwiftUI,則必須建立應用程式委派,並透過 UIApplicationDelegateAdaptor 或 NSApplicationDelegateAdaptor 將其附加至 App 結構。您也必須停用應用程式委派物件重組。詳情請參閱 SwiftUI 操作說明。

    SwiftUI

    @main
    struct YourApp: App {
      // register app delegate for Firebase setup
      @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    
      var body: some Scene {
        WindowGroup {
          NavigationView {
            ContentView()
          }
        }
      }
    }
          
  4. 呼叫 signInAnonymouslyWithCompletion: 方法:

    Swift

    Auth.auth().signInAnonymously { authResult, error in
      // ...
    }

    Objective-C

    [[FIRAuth auth] signInAnonymouslyWithCompletion:^(FIRAuthDataResult * _Nullable authResult,
                                                      NSError * _Nullable error) {
       // ...
     }];
  5. 如果 signInAnonymouslyWithCompletion: 方法順利完成,您可以從 FIRAuthDataResult 物件取得匿名使用者的帳戶資料:

    Swift

    guard let user = authResult?.user else { return }
    let isAnonymous = user.isAnonymous  // true
    let uid = user.uid

    Objective-C

    FIRUser *user = authResult.user;
    BOOL isAnonymous = user.anonymous;  // YES
    NSString *uid = user.uid;

將匿名帳戶轉換為永久帳戶

匿名使用者註冊應用程式後,您可能希望他們能繼續使用新帳戶,例如將使用者在註冊前加入購物車的商品,移至新帳戶的購物車。請以下列步驟完成實作:

  1. 使用者註冊時,請完成使用者驗證服務供應商的登入流程,但不要呼叫任何 FIRAuth.signInWith 方法。例如取得使用者的 Google ID 權杖、Facebook 存取權杖,或電子郵件地址和密碼。
  2. 取得新驗證供應商的 FIRAuthCredential:

    Google 登入
    Swift
    guard
      let authentication = user?.authentication,
      let idToken = authentication.idToken
    else {
      return
    }
    
    let credential = GoogleAuthProvider.credential(withIDToken: idToken,
                                                   accessToken: authentication.accessToken)
    Objective-C
    FIRAuthCredential *credential =
    [FIRGoogleAuthProvider credentialWithIDToken:result.user.idToken.tokenString
                                     accessToken:result.user.accessToken.tokenString];
    Facebook 登入
    Swift
    let credential = FacebookAuthProvider
      .credential(withAccessToken: AccessToken.current!.tokenString)
    Objective-C
    FIRAuthCredential *credential = [FIRFacebookAuthProvider
        credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];
    電子郵件/密碼登入
    Swift
    let credential = EmailAuthProvider.credential(withEmail: email, password: password)
    Objective-C
    FIRAuthCredential *credential =
        [FIREmailAuthProvider credentialWithEmail:email
                                                 password:password];
  3. 將 FIRAuthCredential 物件傳遞至登入使用者的 linkWithCredential:completion: 方法:

    Swift
        user.link(with: credential) { authResult, error in
      // ...
    }
    }
    Objective-C
        [[FIRAuth auth].currentUser linkWithCredential:credential
        completion:^(FIRAuthDataResult *result, NSError *_Nullable error) {
      // ...
    }];

如果對 linkWithCredential:completion: 的呼叫成功,使用者的新帳戶就能存取匿名帳戶的 Firebase 資料。

自動清理

如果已將專案升級至 Firebase Authentication with Identity Platform,可以在 Firebase 控制台啟用自動清理功能。啟用這項功能後,Firebase 就能自動刪除建立至今超過 30 天的匿名帳戶。在啟用自動清理功能的專案中,匿名驗證不會計入用量限制或計費配額。

  • 啟用自動清理功能後建立的任何匿名帳戶,可能會在建立 30 天後隨時自動刪除。
  • 啟用自動清理功能後,現有的匿名帳戶會在 30 天後自動刪除。
  • 如果關閉自動清理功能,系統仍會按照排程刪除匿名帳戶。
  • 如果將匿名帳戶連結至任何登入方式,藉此「升級」帳戶,系統就不會自動刪除該帳戶。

如要在啟用這項功能前,瞭解有多少使用者會受到影響,且已將專案升級至 Firebase Authentication with Identity Platform,您可以在 Cloud Logging 中依 is_anon 篩選。

後續步驟

使用者現在可以透過 Firebase 進行驗證,您可以使用 Firebase 規則,控管他們對 Firebase 資料庫中資料的存取權。