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

使用 C++ 將多個身份驗證提供程序鏈接到一個帳戶

您可以允許用戶使用多個身份驗證提供程序登錄您的應用程序,方法是將身份驗證提供程序憑據鏈接到現有用戶帳戶。用戶可以通過相同的 Firebase 用戶 ID 進行識別,而不管他們用於登錄的身份驗證提供程序如何。例如,使用密碼登錄的用戶可以關聯 Google 帳戶並在未來使用任一方法登錄。或者,匿名用戶可以鏈接 Facebook 帳戶,然後使用 Facebook 登錄以繼續使用您的應用程序。

在你開始之前

向您的應用程序添加對兩個或更多身份驗證提供程序(可能包括匿名身份驗證)的支持。

要將身份驗證提供者憑據鏈接到現有用戶帳戶:

  1. 使用任何身份驗證提供程序或方法登錄用戶。
  2. 完成新身份驗證提供程序的登錄流程,直到但不包括調用firebase::auth::Auth::SignInWithCredential方法之一。例如,獲取用戶的 Google ID 令牌、Facebook 訪問令牌或電子郵件和密碼。
  3. 獲取新身份驗證提供程序的firebase::auth::Credential

    Google 登錄
    firebase::auth::Credential credential =
        firebase::auth::GoogleAuthProvider::GetCredential(google_id_token,
                                                          nullptr);
    
    Facebook 登錄
    firebase::auth::Credential credential =
        firebase::auth::FacebookAuthProvider::GetCredential(access_token);
    
    電子郵件-密碼登錄
    firebase::auth::Credential credential =
        firebase::auth::EmailAuthProvider::GetCredential(email, password);
    
  4. firebase::auth::Credential對像傳遞給登錄用戶的LinkWithCredential方法:

    // Link the new credential to the currently active user.
    firebase::auth::User current_user = auth->current_user();
    firebase::Future<firebase::auth::AuthResult> result =
        current_user.LinkWithCredential(credential);
    

    如果憑據已鏈接到另一個用戶帳戶,則對LinkWithCredential的調用將失敗。在這種情況下,您必鬚根據您的應用程序處理合併帳戶和關聯數據:

    // Gather data for the currently signed in User.
    firebase::auth::User current_user = auth->current_user();
    std::string current_email = current_user.email();
    std::string current_provider_id = current_user.provider_id();
    std::string current_display_name = current_user.display_name();
    std::string current_photo_url = current_user.photo_url();
    
    // Sign in with the new credentials.
    firebase::Future<firebase::auth::AuthResult> result =
        auth->SignInAndRetrieveDataWithCredential(credential);
    
    // To keep example simple, wait on the current thread until call completes.
    while (result.status() == firebase::kFutureStatusPending) {
      Wait(100);
    }
    
    // The new User is now active.
    if (result.error() == firebase::auth::kAuthErrorNone) {
      firebase::auth::User* new_user = *result.result();
    
      // Merge new_user with the user in details.
      // ...
      (void)new_user;
    }
    

如果對LinkWithCredential的調用成功,用戶現在可以使用任何鏈接的身份驗證提供程序登錄並訪問相同的 Firebase 數據。

您可以取消身份驗證提供程序與帳戶的鏈接,以便用戶無法再使用該提供程序登錄。

要取消身份驗證提供程序與用戶帳戶的鏈接,請將提供程序 ID 傳遞給Unlink方法。您可以通過調用ProviderData獲取鏈接到用戶的身份驗證提供程序的提供程序 ID。

// Unlink the sign-in provider from the currently active user.
firebase::auth::User current_user = auth->current_user();
firebase::Future<firebase::auth::AuthResult> result =
    current_user.Unlink(providerId);