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