Microsoft와 C++를 사용하여 인증
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
Firebase SDK를 통해 엔드 투 엔드 로그인 과정을 실행하는 앱에 웹 기반의 일반 OAuth 로그인을 통합하여 사용자가 Microsoft Azure Active Directory와 같은 OAuth 제공업체를 통해 Firebase에 인증하도록 할 수 있습니다.
이 과정은 스마트폰 기반 Firebase SDK를 사용해야 하므로 Android 및 Apple 플랫폼에서만 지원됩니다.
시작하기 전에
- C++ 프로젝트에 Firebase를 추가합니다.
- Firebase Console에서 인증 섹션을 엽니다.
- 로그인 방법 탭에서 Microsoft 제공업체를 사용 설정합니다.
- 해당 제공업체의 개발자 콘솔에서 제공되는 클라이언트 ID 및 클라이언트 보안 비밀번호를 제공업체 구성에 추가합니다.
- Microsoft OAuth 클라이언트를 등록하려면 빠른 시작: Azure Active Directory v2.0 엔드포인트를 사용하여 앱 등록의 안내를 따릅니다.
이 엔드포인트는 Microsoft 개인 계정과 Azure Active Directory 계정을 사용하는 로그인을 지원합니다.
Azure Active Directory v2.0 자세히 알아보기
- 이러한 제공업체에 앱을 등록할 때 프로젝트의
*.firebaseapp.com
도메인을 앱의 리디렉션 도메인으로 등록해야 합니다.
- 저장을 클릭합니다.
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);
Firebase SDK로 로그인 과정 처리하기
Firebase SDK로 로그인 과정을 처리하려면 다음 단계를 따르세요.
Microsoft에 적합한 제공업체 ID로 구성된 FederatedOAuthProviderData
의 인스턴스를 생성합니다.
firebase::auth::FederatedOAuthProviderData
provider_data(firebase::auth::MicrosoftAuthProvider::kProviderId);
선택사항: OAuth 요청과 함께 전송하고자 하는 커스텀 OAuth 매개변수를 추가로 지정합니다.
// Prompt user to re-authenticate to Microsoft.
provider_data.custom_parameters["prompt"] = "login";
// Target specific email with login hint.
provider_data.custom_parameters["login_hint"] =
"user@firstadd.onmicrosoft.com";
Microsoft가 지원하는 매개변수 정보는 Microsoft OAuth 문서를 참조하세요.
Firebase에서 요구하는 매개변수는 setCustomParameters()
와 함께 전달할 수 없습니다. 이러한 매개변수에는 client_id, response_type, redirect_uri, state, scope, response_mode가 있습니다.
특정 Azure AD 테넌트의 사용자만 애플리케이션에 로그인하도록 허용하려면 Azure AD 테넌트의 도메인 이름 또는 테넌트의 GUID 식별자를 사용하면 됩니다. 이렇게 하려면 커스텀 매개변수 객체의 '테넌트' 필드를 지정합니다.
// Optional "tenant" parameter in case you are using an Azure AD tenant.
// eg. '8eaef023-2b34-4da1-9baa-8bc8c9d6a490' or 'contoso.onmicrosoft.com'
// or "common" for tenant-independent tokens.
// The default value is "common".
provider_data.custom_parameters["tenant"] ="TENANT_ID";
선택사항: 인증 제공업체에 요청하고자 하는 기본 프로필 범위를 넘는 OAuth 2.0 범위를 추가로 지정합니다.
provider_data.scopes.push_back("mail.read");
provider_data.scopes.push_back("calendars.read");
자세한 내용은 Microsoft 권한 및 동의 문서를 참조하세요.
제공업체 데이터가 구성되었으면 이를 사용하여
FederatedOAuthProvider
를 만듭니다.
// Construct a FederatedOAuthProvider for use in Auth methods.
firebase::auth::FederatedOAuthProvider provider(provider_data);
인증 제공업체 객체를 사용해 Firebase에 인증합니다. 이는 다른 FirebaseAuth 작업과 달리 사용자가 인증 정보를 입력할 수 있는 웹 보기를 표시하여 UI를 제어합니다.
로그인 과정을 시작하려면 다음과 같이 SignInWithProvider
를 호출합니다.
firebase::Future<firebase::auth::AuthResult> result =
auth->SignInWithProvider(provider_data);
그러면 애플리케이션이 대기하거나
Future에 콜백을 등록할 수 있습니다.
OAuth 액세스 토큰을 사용하면 Microsoft Graph API를 호출할 수 있습니다.
Firebase 인증에서 지원하는 다른 제공업체와 달리, Microsoft는 사진 URL을 제공하지 않습니다. 대신 Microsoft Graph API를 통해 프로필 사진의 바이너리 데이터를 요청해야 합니다.
위의 예시는 로그인 과정에 중점을 두고 있지만 LinkWithProvider
를 사용하여 Microsoft Azure Active Directory 제공업체를 기존 사용자에 연결할 수도 있습니다. 예를 들어 여러 제공업체를 동일한 사용자에 연결하여 그 중 하나로 로그인하도록 허용할 수 있습니다.
firebase::Future<firebase::auth::AuthResult> result = user.LinkWithProvider(provider_data);
최근 로그인한 적이 있어야 진행할 수 있는 중요한 작업에 대해 새로운 사용자 인증 정보를 검색하는 데 사용할 수 있는 ReauthenticateWithProvider
와 동일한 패턴을 사용할 수 있습니다.
firebase::Future<firebase::auth::AuthResult> result =
user.ReauthenticateWithProvider(provider_data);
그러면 애플리케이션이 대기하거나
Future에 콜백을 등록할 수 있습니다.
고급: 수동으로 로그인 과정 처리
OAuth 액세스 토큰 기반의 사용자 인증 정보를 사용하여 직접 로그인할 수 있는 다른 Firebase 지원 OAuth 제공업체(예: Google, Facebook, Twitter)와 달리, Firebase 인증 서버에서 Microsoft OAuth 액세스 토큰의 사용자를 인증할 수 없으므로 Firebase 인증은 Microsoft와 같은 제공업체에 대해 동일한 인증 기능을 지원하지 않습니다.
이는 중요한 보안 요구사항이며 한 프로젝트(공격자)에서 확보한 Microsoft OAuth 액세스 토큰을 다른 프로젝트(피해자)에 로그인하는 데 사용할 수 있는 경우 애플리케이션과 웹사이트가 재전송 공격에 노출될 수 있습니다.
대신 Firebase 인증은 Firebase Console에 구성된 OAuth 클라이언트 ID와 보안 비밀을 사용하여 전체 OAuth 과정과 승인 코드 교환을 처리할 수 있는 기능을 제공합니다. 승인 코드는 특정 클라이언트 ID/보안 비밀과 함께 사용되어야 하므로, 한 프로젝트에서 확보한 승인 코드는 다른 프로젝트에 사용할 수 없습니다.
지원되지 않는 환경에서 이러한 제공업체를 사용해야 하는 경우 서드 파티 OAuth 라이브러리 및 Firebase 커스텀 인증을 사용해야 합니다. 서드 파티 라이브러리는 제공업체 인증에 필요하고 Firebase 커스텀 인증은 제공업체의 사용자 인증 정보를 커스텀 토큰으로 교환할 때 필요합니다.
다음 단계
사용자가 처음으로 로그인하면 신규 사용자 계정이 생성되고 사용자가 로그인할 때 사용한 사용자 인증 정보(사용자 이름과 비밀번호, 전화번호 또는 인증 제공업체 정보)에 연결됩니다. 이 신규 계정은 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,["# Authenticate Using Microsoft and C++\n\nYou can let your users authenticate with Firebase using OAuth providers like\nMicrosoft Azure Active Directory by integrating web-based generic OAuth Login\ninto your app using the Firebase SDK to carry out the end to end sign-in flow.\nSince this flow requires the use of the phone-based Firebase SDKs, it is only\nsupported on Android and Apple platforms.\n\nBefore you begin\n----------------\n\n1. [Add Firebase to your C++ project](/docs/cpp/setup#note_select_platform).\n2. In the [Firebase console](//console.firebase.google.com/), open the **Auth** section.\n3. On the **Sign in method** tab, enable the **Microsoft** provider.\n4. Add the **Client ID** and **Client Secret** from that provider's developer console to the provider configuration:\n 1. To register a Microsoft OAuth client, follow the instructions in [Quickstart: Register an app with the Azure Active Directory v2.0 endpoint](https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-register-an-app). Note that this endpoint supports sign-in using Microsoft personal accounts as well as Azure Active Directory accounts. [Learn more](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-overview) about Azure Active Directory v2.0.\n 2. When registering apps with these providers, be sure to register the `*.firebaseapp.com` domain for your project as the redirect domain for your app.\n5. Click **Save**.\n\nAccess the `firebase::auth::Auth` class\n---------------------------------------\n\nThe `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\nHandle the sign-in flow with the Firebase SDK\n---------------------------------------------\n\nTo handle the sign-in flow with the Firebase SDK, follow these steps:\n\n1. Construct an instance of a `FederatedOAuthProviderData` configured with\n the provider id appropriate for Microsoft.\n\n firebase::auth::FederatedOAuthProviderData\n provider_data(firebase::auth::MicrosoftAuthProvider::kProviderId);\n\n2. **Optional**: Specify additional custom OAuth parameters that you want to\n send with the OAuth request.\n\n // Prompt user to re-authenticate to Microsoft.\n provider_data.custom_parameters[\"prompt\"] = \"login\";\n\n // Target specific email with login hint.\n provider_data.custom_parameters[\"login_hint\"] =\n \"user@firstadd.onmicrosoft.com\";\n\n For the parameters Microsoft supports, see the\n [Microsoft OAuth documentation](https://docs.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code).\n Note that you can't pass Firebase-required parameters with\n `setCustomParameters()`. These parameters are **client_id** ,\n **response_type** , **redirect_uri** , **state** , **scope** and\n **response_mode**.\n\n To allow only users from a particular Azure AD tenant to sign\n into the application, either the friendly domain name of the Azure AD tenant\n or the tenant's GUID identifier can be used. This can be done by specifying\n the \"tenant\" field in the custom parameters object. \n\n // Optional \"tenant\" parameter in case you are using an Azure AD tenant.\n // eg. '8eaef023-2b34-4da1-9baa-8bc8c9d6a490' or 'contoso.onmicrosoft.com'\n // or \"common\" for tenant-independent tokens.\n // The default value is \"common\".\n provider_data.custom_parameters[\"tenant\"] =\"TENANT_ID\";\n\n3. **Optional**: Specify additional OAuth 2.0 scopes beyond basic profile that\n you want to request from the authentication provider.\n\n provider_data.scopes.push_back(\"mail.read\");\n provider_data.scopes.push_back(\"calendars.read\");\n\n To learn more, refer to the\n [Microsoft permissions and consent documentation](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent).\n4. Once your provider data has been configured, use it to create a\n `FederatedOAuthProvider`.\n\n // Construct a FederatedOAuthProvider for use in Auth methods.\n firebase::auth::FederatedOAuthProvider provider(provider_data);\n\n5. Authenticate with Firebase using the Auth provider object. Note that unlike\n other FirebaseAuth operations, this will take control of your UI by popping\n up a web view in which the user can enter their credentials.\n\n To start the sign in flow, call `SignInWithProvider`: \n\n firebase::Future\u003cfirebase::auth::AuthResult\u003e result =\n auth-\u003eSignInWithProvider(provider_data);\n\n Your application may then wait or [register a callback on the Future](#register_callback_on_future).\n\n Using the OAuth access token, you can call the\n [Microsoft Graph API](https://docs.microsoft.com/en-us/graph/overview?toc=./toc.json&view=graph-rest-1.0).\n\n Unlike other providers supported by Firebase Auth, Microsoft does not\n provide a photo URL and instead, the binary data for a profile photo has to\n be requested via\n [Microsoft Graph API](https://docs.microsoft.com/en-us/graph/api/profilephoto-get?view=graph-rest-1.0).\n6. While the above examples focus on sign-in flows, you also have the\n ability to link a Microsoft Azure Active Directory provider to an existing\n user using `LinkWithProvider`. For example, you can link multiple\n providers to the same user allowing them to sign in with either.\n\n firebase::Future\u003cfirebase::auth::AuthResult\u003e result = user.LinkWithProvider(provider_data);\n\n7. The same pattern can be used with `ReauthenticateWithProvider` which can be\n used to retrieve fresh credentials for sensitive operations that require\n recent login.\n\n firebase::Future\u003cfirebase::auth::AuthResult\u003e result =\n user.ReauthenticateWithProvider(provider_data);\n\n Your application may then wait or [register a callback on\n the Future](#register_callback_on_future).\n\nAdvanced: Handle the sign-in flow manually\n------------------------------------------\n\nUnlike other OAuth providers supported by Firebase such as Google, Facebook,\nand Twitter, where sign-in can directly be achieved with OAuth access token\nbased credentials, Firebase Auth does not support the same capability for\nproviders such as Microsoft due to the inability of the Firebase\nAuth server to verify the audience of Microsoft OAuth access tokens.\nThis is a critical security requirement and could expose applications and\nwebsites to replay attacks where a Microsoft OAuth access token obtained for\none project (attacker) can be used to sign in to another project (victim).\nInstead, Firebase Auth offers the ability to handle the entire OAuth flow and\nthe authorization code exchange using the OAuth client ID and secret\nconfigured in the Firebase Console. As the authorization code can only be used\nin conjunction with a specific client ID/secret, an authorization code\nobtained for one project cannot be used with another.\n\nIf these providers are required to be used in unsupported environments, a\nthird party OAuth library and\n[Firebase custom authentication](../admin/create-custom-tokens)\nwould need to be used. The former is needed to authenticate with the provider\nand the latter to exchange the provider's credential for a custom token.\n\nNext steps\n----------\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```"]]