在 Apple 平台上使用 Firebase 進行匿名身份驗證

您可以使用 Firebase 驗證建立並使用臨時匿名帳戶來透過 Firebase 進行驗證。這些臨時匿名帳戶可用於允許尚未註冊您的應用程式的使用者使用受安全規則保護的資料。如果匿名使用者決定註冊您的應用程序,您可以將他們的登入憑證連結到匿名帳戶,以便他們可以在將來的會話中繼續使用受保護的資料。

在你開始之前

  1. 使用 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. -ObjC標誌新增至目標建置設定的「其他連結器標誌」部分。
    6. 完成後,Xcode 將自動開始在背景解析並下載您的依賴項。
  2. 如果您尚未將應用程式連線至 Firebase 項目,請從Firebase 控制台執行此操作。
  3. 啟用匿名身份驗證:
    1. Firebase 控制台中,開啟「驗證」部分。
    2. 登入方法頁面上,啟用匿名登入方法。
    3. 可選:如果您已將專案升級至具有 Identity Platform 的 Firebase 驗證,則可以啟用自動清理。啟用此設定後,超過 30 天的匿名帳戶將自動刪除。在啟用自動清理的項目中,匿名身分驗證將不再計入使用限製或計費配額。請參閱自動清理

使用 Firebase 進行匿名身份驗證

當已登出的使用者使用需要 Firebase 驗證的應用程式功能時,請透過完成以下步驟以匿名方式登入使用者:

  1. UIApplicationDelegate中導入FirebaseCore模組,以及應用程式委託使用的任何其他Firebase 模組。例如,要使用 Cloud Firestore 和身份驗證:

    斯威夫特使用者介面

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

    迅速

    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    Objective-C

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

    斯威夫特使用者介面

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

    迅速

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

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
  3. 如果您使用 SwiftUI,則必須建立應用程式委託並透過UIApplicationDelegateAdaptorNSApplicationDelegateAdaptor將其附加到您的App結構。您還必須停用應用程式委託調配。有關更多信息,請參閱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:方法:

    迅速

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

    Objective-C

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

    迅速

    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登入
    迅速
    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登入
    迅速
    let credential = FacebookAuthProvider
      .credential(withAccessToken: AccessToken.current!.tokenString)
    
    Objective-C
    FIRAuthCredential *credential = [FIRFacebookAuthProvider
        credentialWithAccessToken:[FBSDKAccessToken currentAccessToken].tokenString];
    
    郵件信箱密碼登入
    迅速
    let credential = EmailAuthProvider.credential(withEmail: email, password: password)
    
    Objective-C
    FIRAuthCredential *credential =
        [FIREmailAuthProvider credentialWithEmail:email
                                                 password:password];
    
  3. FIRAuthCredential物件傳遞給登入使用者的linkWithCredential:completion:方法:

    迅速
        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 天,現有匿名帳戶將有資格自動刪除。
  • 如果您關閉自動清理,任何計劃刪除的匿名帳戶仍將保留計劃刪除。
  • 如果您透過將匿名帳戶連結到任何登入方法來「升級」該帳戶,則該帳戶不會自動刪除。

如果您想在啟用此功能之前了解有多少使用者會受到影響,並且您已將專案升級到使用 Identity Platform 進行 Firebase 驗證,則可以在Cloud Logging中按is_anon進行篩選。

下一步

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