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