使用 C++ 將多個驗證供應商連結至帳戶

您可以讓使用者透過多重驗證機制登入您的應用程式 將驗證服務供應商憑證連結至現有使用者帳戶。 無論 用於登入的驗證服務供應商例如登入後 使用密碼可以連結 Google 帳戶,並在 或者,匿名使用者也可以連結 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 方法。您可以取得驗證供應商的供應商 ID ProviderData

// 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);