使用 Facebook 登入和 C++ 進行驗證

只要將 Facebook 登入功能整合至應用程式,即可讓使用者透過 Facebook 帳戶進行 Firebase 驗證。

事前準備

  1. 將 Firebase 新增至 C++ 專案。
  2. 在 Facebook for Developers 網站中,取得應用程式的應用程式 ID 和應用程式密鑰。
  3. 啟用 Facebook 登入功能,做為 Firebase 專案的登入服務供應商:
    1. 在 Firebase 控制台中,依序前往 「Security」(安全性) >「Authentication」(驗證)。
    2. 在「登入方式」分頁中,啟用「Facebook」登入供應商,並指定從 Facebook 取得的「應用程式 ID」和「應用程式密鑰」。
    3. 請前往 Facebook for Developers 網站,在 Facebook 應用程式設定頁面的「Product Settings」>「Facebook Login」設定中,確認您的 OAuth 重新導向 URI (例如 my-app-12345.firebaseapp.com/__/auth/handler) 已列為 OAuth 重新導向 URI 之一。

存取 firebase::auth::Auth 類別

Auth 類別是所有 API 呼叫的閘道。
  1. 新增 Auth 和 App 標頭檔案:
    #include <cassert>
    #include <cinttypes>
    #include <cstdint>
    
    #include "firebase/app.h"
    #include "firebase/auth.h"
  2. 在初始化程式碼中,建立 firebase::App 類別。
    #if defined(__ANDROID__)
      firebase::App* app =
          firebase::App::Create(firebase::AppOptions(), my_jni_env, my_activity);
    #else
      firebase::App* app = firebase::App::Create(firebase::AppOptions());
    #endif  // defined(__ANDROID__)
  3. 取得 firebase::App 的 firebase::auth::Auth 類別。App 和 Auth 之間是一對一對應關係。
    firebase::auth::Auth* auth = firebase::auth::Auth::GetAuth(app);

使用 Firebase 驗證

  1. 請按照 Android 和 iOS+ 的操作說明,取得已登入 Facebook 使用者的存取權杖。
  2. 使用者成功登入後,請將存取權杖換成 Firebase 憑證,並使用 Firebase 憑證向 Firebase 進行驗證:
    firebase::auth::Credential credential =
        firebase::auth::FacebookAuthProvider::GetCredential(access_token);
    firebase::Future<firebase::auth::AuthResult> result =
        auth->SignInAndRetrieveDataWithCredential(credential);
  3. 如果程式有定期執行的更新迴圈 (例如每秒 30 或 60 次),您可以使用 Auth::SignInAndRetrieveDataWithCredentialLastResult 每次更新檢查一次結果:
    firebase::Future<firebase::auth::AuthResult> result =
        auth->SignInAndRetrieveDataWithCredentialLastResult();
    if (result.status() == firebase::kFutureStatusComplete) {
      if (result.error() == firebase::auth::kAuthErrorNone) {
        firebase::auth::AuthResult auth_result = *result.result();
        printf("Sign in succeeded for `%s`\n",
               auth_result.user.display_name().c_str());
      } else {
        printf("Sign in failed with error '%s'\n", result.error_message());
      }
    }
    或者,如果您的程式是由事件驅動,建議您在 Future 上註冊回呼。

在 Future 上註冊回呼

部分程式的 Update 函式每秒會呼叫 30 或 60 次。舉例來說,許多遊戲都採用這種模式。這些程式可以呼叫 LastResult 函式,輪詢非同步呼叫。不過,如果程式是由事件驅動,您可能偏好註冊回呼函式。Future 完成後,系統會呼叫回呼函式。
void OnCreateCallback(const firebase::Future<firebase::auth::User*>& result,
                      void* user_data) {
  // The callback is called when the Future enters the `complete` state.
  assert(result.status() == firebase::kFutureStatusComplete);

  // Use `user_data` to pass-in program context, if you like.
  MyProgramContext* program_context = static_cast<MyProgramContext*>(user_data);

  // Important to handle both success and failure situations.
  if (result.error() == firebase::auth::kAuthErrorNone) {
    firebase::auth::User* user = *result.result();
    printf("Create user succeeded for email %s\n", user->email().c_str());

    // Perform other actions on User, if you like.
    firebase::auth::User::UserProfile profile;
    profile.display_name = program_context->display_name;
    user->UpdateUserProfile(profile);

  } else {
    printf("Created user failed with error '%s'\n", result.error_message());
  }
}

void CreateUser(firebase::auth::Auth* auth) {
  // Callbacks work the same for any firebase::Future.
  firebase::Future<firebase::auth::AuthResult> result =
      auth->CreateUserWithEmailAndPasswordLastResult();

  // `&my_program_context` is passed verbatim to OnCreateCallback().
  result.OnCompletion(OnCreateCallback, &my_program_context);
}
您也可以視需要將回呼函式設為 lambda。
void CreateUserUsingLambda(firebase::auth::Auth* auth) {
  // Callbacks work the same for any firebase::Future.
  firebase::Future<firebase::auth::AuthResult> result =
      auth->CreateUserWithEmailAndPasswordLastResult();

  // The lambda has the same signature as the callback function.
  result.OnCompletion(
      [](const firebase::Future<firebase::auth::User*>& result,
         void* user_data) {
        // `user_data` is the same as &my_program_context, below.
        // Note that we can't capture this value in the [] because std::function
        // is not supported by our minimum compiler spec (which is pre C++11).
        MyProgramContext* program_context =
            static_cast<MyProgramContext*>(user_data);

        // Process create user result...
        (void)program_context;
      },
      &my_program_context);
}

後續步驟

使用者首次登入後,系統會建立新的使用者帳戶,並連結至使用者登入時使用的憑證,也就是使用者名稱和密碼、電話號碼或驗證提供者資訊。這個新帳戶會儲存為 Firebase 專案的一部分,可用於識別專案中所有應用程式的使用者,無論使用者如何登入。

  • 在應用程式中,您可以從 firebase::auth::User 物件取得使用者的基本個人資料資訊:

    firebase::auth::User user = auth->current_user();
    if (user.is_valid()) {
      std::string name = user.display_name();
      std::string email = user.email();
      std::string photo_url = user.photo_url();
      // The user's ID, unique to the Firebase project.
      // Do NOT use this value to authenticate with your backend server,
      // if you have one. Use firebase::auth::User::Token() instead.
      std::string uid = user.uid();
    }
  • 在 Firebase Realtime Database 和 Cloud Storage安全性規則中,您可以從 auth 變數取得已登入使用者的專屬使用者 ID,並用來控管使用者可存取的資料。

您可以將驗證供應商憑證連結至現有使用者帳戶,允許使用者透過多個驗證供應商登入應用程式。

如要登出使用者,請呼叫 SignOut():

auth->SignOut();