您可以使用 Firebase Authentication,讓使用者透過電子郵件地址和密碼向 Firebase 驗證身分,並管理應用程式的密碼型帳戶。
事前準備
- 將 Firebase 新增至 C++ 專案。
- 如果尚未將應用程式連結至 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
之間是一對一的對應關係。firebase::auth::Auth* auth = firebase::auth::Auth::GetAuth(app);
建立密碼帳戶
如要建立含有密碼的新使用者帳戶,請在應用程式的登入程式碼中完成下列步驟:
- 當新使用者透過應用程式的註冊表單註冊時,請完成應用程式要求的任何新帳戶驗證步驟,例如確認新帳戶的密碼輸入正確,且符合複雜度規定。
- 將新使用者的電子郵件地址和密碼傳遞至
Auth::CreateUserWithEmailAndPassword
,建立新帳戶:firebase::Future<firebase::auth::AuthResult> result = auth->CreateUserWithEmailAndPassword(email, password);
- 如果程式有定期執行的更新迴圈 (例如每秒 30 或 60 次),您可以使用
Auth::CreateUserWithEmailAndPasswordLastResult
,在每次更新時檢查結果: 或者,如果您的程式是以事件為導向,您可能會偏好在 Future 上註冊回呼。firebase::Future<firebase::auth::AuthResult> result = auth->CreateUserWithEmailAndPasswordLastResult(); if (result.status() == firebase::kFutureStatusComplete) { if (result.error() == firebase::auth::kAuthErrorNone) { const firebase::auth::AuthResult auth_result = *result.result(); printf("Create user succeeded for email %s\n", auth_result.user.email().c_str()); } else { printf("Created user failed with error '%s'\n", result.error_message()); } }
透過電子郵件地址和密碼登入使用者帳戶
使用密碼登入使用者的步驟,與建立新帳戶的步驟類似。在應用程式的登入函式中,請執行下列操作:
- 使用者登入應用程式時,請將使用者的電子郵件地址和密碼傳遞至
firebase::auth::Auth::SignInWithEmailAndPassword
:firebase::Future<firebase::auth::AuthResult> result = auth->SignInWithEmailAndPassword(email, password);
- 如果程式有定期執行的更新迴圈 (例如每秒 30 或 60 次),您可以使用
Auth::SignInWithEmailAndPasswordLastResult
,在每次更新時檢查結果: 或者,如果您的程式是以事件為導向,您可能會偏好在 Future 上註冊回呼。firebase::Future<firebase::auth::AuthResult> result = auth->SignInWithEmailAndPasswordLastResult(); if (result.status() == firebase::kFutureStatusComplete) { if (result.error() == firebase::auth::kAuthErrorNone) { const firebase::auth::AuthResult auth_result = *result.result(); printf("Sign in succeeded for email %s\n", auth_result.user.email().c_str()); } else { printf("Sign in failed with error '%s'\n", result.error_message()); } }
在 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); }
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 控制台的「Authentication Settings」頁面中,開啟「Password policy」分頁:
Firebase Authentication 密碼政策支援下列密碼規定:
須有小寫字元
須有大寫字元
必須包含數字字元
須有非英數字元
下列字元符合非英數字元規定:
^ $ * . [ ] { } ( ) ? " ! @ # % & / \ , > < ' : ; | _ ~
密碼長度下限 (6 到 30 個字元,預設為 6 個字元)
密碼長度上限 (最多 4096 個半形字元)
您可以透過下列兩種模式強制執行密碼政策:
要求:使用者如未改用符合政策的密碼,就無法註冊。
通知:使用者可以註冊不符合規定的密碼。使用這個模式時,您應在用戶端檢查使用者的密碼是否符合政策規定,如果不符合,請以某種方式提示使用者更新密碼。
新使用者一律須選擇符合政策的密碼。
如果您有活躍使用者,建議不要啟用「登入時強制升級」,除非您打算禁止密碼不符合政策的使用者存取帳戶。請改用通知模式,讓使用者以目前的密碼登入,並告知他們密碼不符合哪些規定。
建議:啟用電子郵件列舉防護功能
如果電子郵件地址必須註冊但未註冊 (例如使用電子郵件地址和密碼登入時),或必須未使用但已註冊 (例如變更使用者的電子郵件地址時),部分以電子郵件地址做為參數的 Firebase Authentication 方法會擲回特定錯誤。雖然這有助於向使用者建議特定解決方法,但惡意行為人也可能濫用這項功能,找出使用者註冊的電子郵件地址。
為降低這類風險,建議您使用 Google Cloud gcloud
工具,為專案啟用電子郵件列舉保護機制。請注意,啟用這項功能會變更 Firebase Authentication 的錯誤回報行為,請確保應用程式不會依賴更具體的錯誤。
後續步驟
使用者首次登入後,系統會建立新的使用者帳戶,並連結至使用者登入時使用的憑證 (即使用者名稱和密碼、電話號碼或驗證供應商資訊)。這個新帳戶會儲存在 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, 並使用該 ID 控制使用者可存取的資料。
您可以將驗證供應商憑證連結至現有使用者帳戶,允許使用者透過多個驗證供應商登入應用程式。
如要登出使用者,請呼叫
SignOut()
:
auth->SignOut();