Google ログインと C++ を使用して認証する

Google ログインをアプリに統合して、ユーザーが Firebase での認証に Google アカウントを使用できるようにすることができます。

始める前に

  1. Firebase を C++ プロジェクトに追加します
  2. Firebase コンソールで、ログイン方法として Google を有効にします。
    1. Firebase コンソールで [Authentication] セクションを開きます。
    2. [Sign-in method] タブで [Google] を有効にし、[保存] をクリックします。
  3. コンソールでプロンプトが表示されたら、更新された Firebase 構成ファイル(google-services.json)をダウンロードします。このファイルには、Google ログインに必要な OAuth クライアント情報が含まれています。
  4. この最新の構成ファイルを Android Studio プロジェクトに移動し、対応する古い構成ファイルを置き換えますAndroid プロジェクトに Firebase を追加するをご覧ください)。

firebase::auth::Auth クラスへのアクセス

すべての API 呼び出しは Auth クラスを使用して行われます。
  1. Auth ヘッダー ファイルと App ヘッダー ファイルを追加します。
    #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::Appfirebase::auth::Auth クラスを取得します。AppAuth は、1 対 1 で対応しています。
    firebase::auth::Auth* auth = firebase::auth::Auth::GetAuth(app);
    

Firebase で認証する

  1. Android 用と iOS+ 用の手順に沿って、Google ログイン用の ID トークンを取得します。
  2. ユーザーがログインに成功したら、トークンを Firebase 認証情報と交換し、Firebase 認証情報を使用して Firebase での認証を行います。
    firebase::auth::Credential credential =
        firebase::auth::GoogleAuthProvider::GetCredential(google_id_token,
                                                          nullptr);
    firebase::Future<firebase::auth::AuthResult> result =
        auth->SignInAndRetrieveDataWithCredential(credential);
    
  3. 定期的に(たとえば、毎秒 30 回または 60 回)実行される更新ループがプログラムに含まれている場合、Auth::SignInAndRetrieveDataWithCredentialLastResult を使用して、更新されるたびに 1 回結果を確認できます。
    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 にコールバックを登録する

プログラムの中には、毎秒 30 回または 60 回呼び出される Update 関数が含まれるものがあります。たとえば、多くのゲームでこのモデルが使用されています。このようなプログラムでは、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);
}
コールバック関数にラムダを使用することもできます。
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 のセキュリティ ルールでは、ログイン済みユーザーの一意のユーザー ID を auth 変数から取得し、それを使用して、ユーザーがアクセスできるデータを管理できます。

既存のユーザー アカウントに認証プロバイダの認証情報をリンクすることで、ユーザーは複数の認証プロバイダを使用してアプリにログインできるようになります。

ユーザーのログアウトを行うには、SignOut() を呼び出します。

auth->SignOut();