Firebase Authentication を使用すると、ユーザーがメール アドレスとパスワードを使用して Firebase で認証できるようにし、アプリのパスワード ベースのアカウントを管理できます。
あなたが始める前に
- C++ プロジェクトに Firebase を追加します。
- アプリを Firebase プロジェクトにまだ接続していない場合は、 Firebase コンソールから接続します。
- メール/パスワードによるサインインを有効にする:
- Firebase コンソールで、 Authセクションを開きます。
- [サインイン方法] タブで、電子メール/パスワードによるサインイン方法を有効にして、[保存] をクリックします。
firebase::auth::Auth
クラスにアクセスする
Auth
クラスは、すべての API 呼び出しのゲートウェイです。- Auth および App ヘッダー ファイルを追加します:
#include "firebase/app.h" #include "firebase/auth.h"
- 初期化コードで、
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__)
-
firebase::App
のfirebase::auth::Auth
クラスを取得します。App
とAuth
の間には 1 対 1 のマッピングがあります。firebase::auth::Auth* auth = firebase::auth::Auth::GetAuth(app);
パスワードベースのアカウントを作成する
パスワードを使用して新しいユーザー アカウントを作成するには、アプリのサインイン コードで次の手順を実行します。
- 新しいユーザーがアプリのサインアップ フォームを使用してサインアップするときは、新しいアカウントのパスワードが正しく入力され、複雑さの要件を満たしていることを確認するなど、アプリで必要な新しいアカウントの検証手順を完了します。
- 新しいユーザーの電子メールアドレスとパスワードを
Auth::CreateUserWithEmailAndPassword
に渡すことで、新しいアカウントを作成します:firebase::Future<firebase::auth::User*> result = auth->CreateUserWithEmailAndPassword(email, password);
- プログラムに定期的に実行される更新ループがある場合 (たとえば、1 秒あたり 30 回または 60 回)、更新ごとに
Auth::CreateUserWithEmailAndPasswordLastResult
:firebase::Future<firebase::auth::User*> result = auth->CreateUserWithEmailAndPasswordLastResult(); if (result.status() == firebase::kFutureStatusComplete) { if (result.error() == firebase::auth::kAuthErrorNone) { firebase::auth::User* user = *result.result(); printf("Create user succeeded for email %s\n", user->email().c_str()); } else { printf("Created user failed with error '%s'\n", result.error_message()); } }
を使用して結果を確認できます。 Future にコールバックを登録します。
メールアドレスとパスワードを使用してユーザーにサインインする
パスワードを使用してユーザーをサインインする手順は、新しいアカウントを作成する手順と似ています。アプリのサインイン機能で、次の操作を行います。
- ユーザーがアプリにサインインするときに、ユーザーのメール アドレスとパスワードを
firebase::auth::Auth::SignInWithEmailAndPassword
に渡します:firebase::Future<firebase::auth::User*> result = auth->SignInWithEmailAndPassword(email, password);
- プログラムに定期的に実行される更新ループがある場合 (たとえば、1 秒あたり 30 回または 60 回)、更新ごとに
Auth::SignInWithEmailAndPasswordLastResult
:firebase::Future<firebase::auth::User*> result = auth->SignInWithEmailAndPasswordLastResult(); if (result.status() == firebase::kFutureStatusComplete) { if (result.error() == firebase::auth::kAuthErrorNone) { firebase::auth::User* user = *result.result(); printf("Sign in succeeded for email %s\n", user->email().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::User*> 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::User*> 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 Authentication メソッドでは、登録が必要なときにメール アドレスが登録されていない場合 (たとえば、メール アドレスとパスワードを使用してサインインする場合)、または未使用である必要があるときに登録された場合 (たとえば、ユーザーのメールアドレスを変更する場合)。これは、ユーザーに特定の救済策を提案するのに役立ちますが、悪意のあるアクターが悪用して、ユーザーが登録した電子メール アドレスを発見することもできます。
このリスクを軽減するには、Google Cloud のgcloud
ツールを使用して、プロジェクトのメール列挙保護を有効にすることをお勧めします。この機能を有効にすると、Firebase Authentication のエラー報告の動作が変わることに注意してください。アプリがより具体的なエラーに依存していないことを確認してください。
次のステップ
ユーザーが初めてサインインすると、新しいユーザー アカウントが作成され、サインインに使用したユーザーの資格情報 (ユーザー名とパスワード、電話番号、または認証プロバイダー情報) にリンクされます。この新しいアカウントは Firebase プロジェクトの一部として保存され、ユーザーのサインイン方法に関係なく、プロジェクト内のすべてのアプリでユーザーを識別するために使用できます。
アプリでは、
firebase::auth::User
オブジェクトからユーザーの基本的なプロフィール情報を取得できます。firebase::auth::User* user = auth->current_user(); if (user != nullptr) { 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();