커스텀 인증 시스템과 C++를 사용하여 Firebase 인증하기
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
사용자가 정상적으로 로그인할 때 커스텀 서명 토큰을 발행하도록 인증 서버를 수정하면 Firebase Authentication에 커스텀 인증 시스템을 통합할 수 있습니다. 그러면 앱이 이 토큰을 받아 Firebase 인증에 사용합니다.
시작하기 전에
- C++ 프로젝트에 Firebase를 추가합니다.
- 다음과 같이 프로젝트의 서버 키를 가져옵니다.
- 프로젝트 설정의 서비스 계정
페이지로 이동합니다.
- 서비스 계정 페이지의 Firebase Admin SDK 섹션 하단에서
새 비공개 키 생성을 클릭합니다.
- 새 서비스 계정의 공개 키/비공개 키 쌍이 자동으로 컴퓨터에
저장됩니다. 이 파일을 인증 서버에 복사합니다.
Firebase 인증
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::SignInWithCustomToken
를 호출합니다.
- 사용자가 앱에 로그인하면 사용자의 로그인 인증 정보(예: 사용자 이름과 비밀번호)를 인증 서버로 전송하세요. 서버가 사용자 인증 정보를 확인하여 정보가 유효하면 커스텀 토큰을 반환합니다.
- 인증 서버에서 커스텀 토큰을 받은 후 다음과 같이 이 토큰을
Auth::SignInWithCustomToken
에 전달하여 사용자를 로그인 처리합니다.
firebase::Future<firebase::auth::AuthResult> result =
auth->SignInWithCustomToken(custom_token);
- 프로그램에 정기적으로 실행되는 업데이트 루프(예: 초당 30회 또는 60회)가 있는 경우 다음과 같이
Auth::SignInWithCustomTokenLastResult
를 사용해 업데이트 시마다 한 번씩 결과를 확인할 수 있습니다.firebase::Future<firebase::auth::AuthResult> result =
auth->SignInWithCustomTokenLastResult();
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에 콜백을 등록하는 것이 나을 수도 있습니다.
다음 단계
사용자가 처음으로 로그인하면 신규 사용자 계정이 생성되고 사용자가 로그인할 때 사용한 사용자 인증 정보(사용자 이름과 비밀번호, 전화번호 또는 인증 제공업체 정보)에 연결됩니다. 이 신규 계정은 Firebase 프로젝트에 저장되며 사용자의 로그인 방법과 무관하게 프로젝트 내의 모든 앱에서 사용자를 식별하는 데 사용할 수 있습니다.
인증 제공업체의 사용자 인증 정보를 기존 사용자 계정에 연결하면 사용자가 여러 인증 제공업체를 통해 앱에 로그인할 수 있습니다.
사용자를 로그아웃시키려면 SignOut()
을 호출합니다.
auth->SignOut();
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-08-16(UTC)
[null,null,["최종 업데이트: 2025-08-16(UTC)"],[],[],null,["You can integrate Firebase Authentication with a custom authentication system by\nmodifying your authentication server to produce custom signed tokens when a user\nsuccessfully signs in. Your app receives this token and uses it to authenticate\nwith Firebase.\n\nBefore you begin\n\n1. [Add Firebase to your C++\n project](/docs/cpp/setup#note_select_platform).\n2. Get your project's server keys:\n 1. Go to the [Service Accounts](https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk) page in your project's settings.\n 2. Click *Generate New Private Key* at the bottom of the *Firebase Admin SDK* section of the *Service Accounts* page.\n 3. The new service account's public/private key pair is automatically saved on your computer. Copy this file to your authentication server.\n\nAuthenticate with Firebase The `Auth` class is the gateway for all API calls.\n\n1. Add the Auth and App header files: \n\n ```c++\n #include \"firebase/app.h\"\n #include \"firebase/auth.h\"\n ```\n2. In your initialization code, create a [`firebase::App`](/docs/reference/cpp/class/firebase/app) class. \n\n ```c++\n #if defined(__ANDROID__)\n firebase::App* app =\n firebase::App::Create(firebase::AppOptions(), my_jni_env, my_activity);\n #else\n firebase::App* app = firebase::App::Create(firebase::AppOptions());\n #endif // defined(__ANDROID__)\n ```\n3. Acquire the `firebase::auth::Auth` class for your `firebase::App`. There is a one-to-one mapping between `App` and `Auth`. \n\n ```c++\n firebase::auth::Auth* auth = firebase::auth::Auth::GetAuth(app);\n ```\n\nCall `Auth::SignInWithCustomToken` with the token from your authentication server.\n\n1. When users sign in to your app, send their sign-in credentials (for example, their username and password) to your authentication server. Your server checks the credentials and returns a [custom token](/docs/auth/admin/create-custom-tokens) if they are valid.\n2. After you receive the custom token from your authentication server, pass it to `Auth::SignInWithCustomToken` to sign in the user: \n\n ```c++\n firebase::Future\u003cfirebase::auth::AuthResult\u003e result =\n auth-\u003eSignInWithCustomToken(custom_token);\n ```\n3. If your program has an update loop that runs regularly (say at 30 or 60 times per second), you can check the results once per update with `Auth::SignInWithCustomTokenLastResult`: \n\n ```c++\n firebase::Future\u003cfirebase::auth::AuthResult\u003e result =\n auth-\u003eSignInWithCustomTokenLastResult();\n if (result.status() == firebase::kFutureStatusComplete) {\n if (result.error() == firebase::auth::kAuthErrorNone) {\n firebase::auth::AuthResult auth_result = *result.result();\n printf(\"Sign in succeeded for `%s`\\n\",\n auth_result.user.display_name().c_str());\n } else {\n printf(\"Sign in failed with error '%s'\\n\", result.error_message());\n }\n }\n ```\n Or, if your program is event driven, you may prefer to [register a callback on the\n Future](#register_callback_on_future).\n\nNext steps\n\nAfter a user signs in for the first time, a new user account is created and\nlinked to the credentials---that is, the user name and password, phone\nnumber, or auth provider information---the user signed in with. This new\naccount is stored as part of your Firebase project, and can be used to identify\na user across every app in your project, regardless of how the user signs in.\n\n- In your apps, you can get the user's basic profile information from the\n [`firebase::auth::User`](/docs/reference/cpp/class/firebase/auth/user) object:\n\n ```c++\n firebase::auth::User user = auth-\u003ecurrent_user();\n if (user.is_valid()) {\n std::string name = user.display_name();\n std::string email = user.email();\n std::string photo_url = user.photo_url();\n // The user's ID, unique to the Firebase project.\n // Do NOT use this value to authenticate with your backend server,\n // if you have one. Use firebase::auth::User::Token() instead.\n std::string uid = user.uid();\n }\n ```\n- In your Firebase Realtime Database and Cloud Storage\n [Security Rules](/docs/database/security/user-security), you can\n get the signed-in user's unique user ID from the `auth` variable,\n and use it to control what data a user can access.\n\nYou can allow users to sign in to your app using multiple authentication\nproviders by [linking auth provider credentials to an\nexisting user account.](/docs/auth/cpp/account-linking)\n\nTo sign out a user, call [`SignOut()`](/docs/reference/cpp/class/firebase/auth/auth#signout): \n\n```c++\nauth-\u003eSignOut();\n```"]]