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

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

您可以使用 Firebase 身份驗證創建並使用臨時匿名帳戶來通過 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 將自動開始在後台解析並下載您的依賴項。

接下來,執行一些配置步驟:

  1. 如果您尚未將應用連接到 Firebase 項目,請從Firebase 控制台執行此操作。
  2. 啟用匿名身份驗證:
    1. Firebase 控制台中,打開“身份驗證”部分。
    2. 登錄方法頁面上,啟用匿名登錄方法。
    3. 可選:啟用自動清理。啟用此設置後,超過 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

    谷歌登錄
    迅速
    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 控制台中啟用自動清理功能時,超過 30 天的匿名帳戶將被自動刪除。啟用此設置可防止您的用戶數據庫填充未使用的帳戶。在啟用自動清理的項目中,匿名身份驗證將不計入使用限製或計費配額。

  • 啟用自動清理後創建的任何匿名帳戶都將在創建後 30 天被刪除。
  • 啟用自動清理之前創建的匿名帳戶將在啟用自動清理後約 30 天被刪除。
  • 如果您關閉自動清理,任何計劃刪除的匿名帳戶仍將保留計劃刪除。
  • 如果您通過將匿名帳戶鏈接到任何登錄方法來“升級”該帳戶,則該帳戶不會被自動刪除。

如果您想在啟用此功能之前了解有多少用戶會受到影響,並且您已將項目升級到使用 Identity Platform 進行 Firebase 身份驗證,則可以在Cloud Logging中按is_anon進行過濾。

下一步

現在,用戶可以通過 Firebase 進行身份驗證,您可以使用Firebase 規則控制他們對 Firebase 數據庫中數據的訪問。