Firebase 인증을 사용하면 사용자가 이메일 주소와 비밀번호를 사용하여 Firebase에 인증하고 앱의 비밀번호 기반 계정을 관리할 수 있습니다.
시작하기 전에
- C++ 프로젝트에 Firebase를 추가합니다 .
- 앱을 Firebase 프로젝트에 아직 연결하지 않았다면 Firebase 콘솔 에서 연결하세요.
- 이메일/비밀번호 로그인 활성화:
- Firebase 콘솔 에서 인증 섹션을 엽니다.
- 로그인 방법 탭에서 이메일/비밀번호 로그인 방법을 활성화하고 저장 을 클릭합니다.
firebase::auth::Auth
클래스에 액세스합니다.
Auth
클래스는 모든 API 호출의 게이트웨이입니다.- 인증 및 앱 헤더 파일 추가:
#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::User*> result = auth->CreateUserWithEmailAndPassword(email, password);
에 전달하여 새 계정을 만듭니다. - 프로그램에 정기적으로 실행되는 업데이트 루프가 있는 경우(예: 초당 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);
전달합니다. - 프로그램에 정기적으로 실행되는 업데이트 루프가 있는 경우(예: 초당 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 인증 방법은 이메일 주소를 등록해야 할 때(예: 이메일 주소와 비밀번호로 로그인할 때) 등록을 취소하거나 사용하지 않아야 할 때(예: 사용자의 이메일 주소를 변경할 때). 이는 사용자에게 특정 해결 방법을 제안하는 데 도움이 될 수 있지만 악의적인 행위자가 사용자가 등록한 이메일 주소를 발견하는 데 악용될 수도 있습니다.
이 위험을 완화하려면 Google Cloud gcloud
도구를 사용하여 프로젝트에 대한 이메일 열거 보호를 사용 설정 하는 것이 좋습니다. 이 기능을 활성화하면 Firebase 인증의 오류 보고 동작이 변경됩니다. 앱이 보다 구체적인 오류에 의존하지 않는지 확인하세요.
다음 단계
사용자가 처음으로 로그인하면 새 사용자 계정이 생성되고 사용자가 로그인할 때 사용한 자격 증명(즉, 사용자 이름과 암호, 전화 번호 또는 인증 공급자 정보)에 연결됩니다. 이 새 계정은 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 실시간 데이터베이스 및 Cloud Storage 보안 규칙 에서
auth
변수에서 로그인한 사용자의 고유한 사용자 ID를 가져와 사용자가 액세스할 수 있는 데이터를 제어하는 데 사용할 수 있습니다.
인증 공급자 자격 증명을 기존 사용자 계정에 연결하여 사용자가 여러 인증 공급자를 사용하여 앱에 로그인하도록 허용할 수 있습니다.
사용자를 로그아웃하려면 SignOut()
을 호출합니다.
auth->SignOut();