使用 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);

疑難排解

如果嘗試連結多個帳戶時發生錯誤,請參閱已驗證電子郵件地址的說明文件。