在 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. -ObjC 標記新增至目標建構設定的「Other Linker Flags」部分。
    6. 完成後,Xcode 會自動開始在背景中解析並下載依附元件。
  2. 如果尚未將應用程式連結至 Firebase 專案,請從 Firebase 控制台進行連結。
  3. 啟用匿名驗證:
    1. Firebase 控制台中,開啟「Auth」(驗證) 部分。
    2. 在「登入方式」頁面中,啟用「匿名」登入方式。
    3. 選用:如果已將專案升級至 Firebase Authentication with Identity Platform,可以啟用自動清除功能。啟用這項設定後,系統就會自動刪除建立至今超過 30 天的匿名帳戶。在啟用自動清除功能的專案中,匿名驗證將不再計入用量限制或計費配額。請參閱「自動清除」一節。

以匿名方式向 Firebase 進行驗證

如果使用者在登出後使用需要透過 Firebase 驗證身分的應用程式功能,請完成下列步驟,以匿名方式登入使用者:

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

    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,就必須建立應用程式委派,並透過 UIApplicationDelegateAdaptorNSApplicationDelegateAdaptor 將其附加至 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 資料庫中資料的存取權。