通過將身份驗證提供程序憑據鏈接到現有用戶帳戶,可以允許用戶使用多個身份驗證提供程序登錄您的應用程序。無論用戶使用哪種身份驗證提供者登錄,都可以使用相同的Firebase用戶ID來識別用戶。例如,使用密碼登錄的用戶將來可以鏈接Google帳戶並使用這兩種方法登錄。或者,匿名用戶可以鏈接Facebook帳戶,然後再登錄Facebook以繼續使用您的應用程序。
在你開始之前
向您的應用添加對兩個或多個身份驗證提供程序(可能包括匿名身份驗證)的支持。
將身份驗證提供者憑據鏈接到用戶帳戶
要將身份驗證提供程序憑據鏈接到現有用戶帳戶,請執行以下操作:
- 使用任何身份驗證提供程序或方法登錄用戶。
- 完成新身份驗證提供程序的登錄流程,但不包括調用
firebase::auth::Auth::SignInWithCredential
方法之一,但不包括firebase::auth::Auth::SignInWithCredential
操作。例如,獲取用戶的Google ID令牌,Facebook訪問令牌或電子郵件和密碼。 為新的身份驗證提供程序獲取
Google登錄firebase::auth::Credential
: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);
將
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::User*> 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::User*> result = auth->SignInWithCredential(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::User*> result = current_user->Unlink(providerId);