Android에서 커스텀 인증 시스템을 사용하여 Firebase에 인증
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
사용자가 정상적으로 로그인할 때 커스텀 서명 토큰을 발행하도록 인증 서버를 수정하면 Firebase Authentication에 커스텀 인증 시스템을 통합할 수 있습니다. 그러면 앱이 이 토큰을 받아 Firebase 인증에 사용합니다.
시작하기 전에
- 아직 추가하지 않았다면 Android 프로젝트에 Firebase를 추가합니다.
-
모듈(앱 수준) Gradle 파일(일반적으로
<project>/<app-module>/build.gradle.kts
또는 <project>/<app-module>/build.gradle
)에서 Android용 Firebase Authentication 라이브러리의 종속 항목을 추가합니다. 라이브러리 버전 관리 제어에는 Firebase Android BoM을 사용하는 것이 좋습니다.
dependencies {
// Import the BoM for the Firebase platform
implementation(platform("com.google.firebase:firebase-bom:34.1.0"))
// Add the dependency for the Firebase Authentication library
// When using the BoM, you don't specify versions in Firebase library dependencies
implementation("com.google.firebase:firebase-auth")
}
Firebase Android BoM을 사용하면 앱에서 항상 호환되는 Firebase Android 라이브러리 버전만 사용합니다.
(대안)
BoM을 사용하지 않고 Firebase 라이브러리 종속 항목을 추가합니다.
Firebase BoM을 사용하지 않도록 선택한 경우에는 종속 항목 줄에 각 Firebase 라이브러리 버전을 지정해야 합니다.
앱에서 여러 Firebase 라이브러리를 사용하는 경우 모든 버전이 호환되도록 BoM을 사용하여 라이브러리 버전을 관리하는 것이 좋습니다.
dependencies {
// Add the dependency for the Firebase Authentication library
// When NOT using the BoM, you must specify versions in Firebase library dependencies
implementation("com.google.firebase:firebase-auth:24.0.1")
}
- 다음과 같이 프로젝트의 서버 키를 가져옵니다.
- 프로젝트 설정의 서비스 계정
페이지로 이동합니다.
- 서비스 계정 페이지의 Firebase Admin SDK 섹션 하단에서
새 비공개 키 생성을 클릭합니다.
- 새 서비스 계정의 공개 키/비공개 키 쌍이 자동으로 컴퓨터에
저장됩니다. 이 파일을 인증 서버에 복사합니다.
Firebase 인증
- 다음과 같이 로그인 작업의
onCreate
메서드에서 FirebaseAuth
객체의 공유 인스턴스를 가져옵니다.
Kotlin
private lateinit var auth: FirebaseAuth
// ...
// Initialize Firebase Auth
auth = Firebase.auth
Java
private FirebaseAuth mAuth;
// ...
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
- 활동을 초기화할 때 사용자가 현재 로그인되어 있는지 확인합니다.
Kotlin
public override fun onStart() {
super.onStart()
// Check if user is signed in (non-null) and update UI accordingly.
val currentUser = auth.currentUser
updateUI(currentUser)
}
Java
@Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
- 사용자가 앱에 로그인하면 사용자의 로그인 인증 정보(예: 사용자 이름과 비밀번호)를 인증 서버로 전송하세요. 서버가 사용자 인증 정보를 확인하여 정보가 유효하면 커스텀 토큰을 반환합니다.
- 인증 서버에서 커스텀 토큰을 받은 후 다음과 같이 이 토큰을
signInWithCustomToken
에 전달하여 사용자를 로그인 처리합니다.
Kotlin
customToken?.let {
auth.signInWithCustomToken(it)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCustomToken:success")
val user = auth.currentUser
updateUI(user)
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCustomToken:failure", task.exception)
Toast.makeText(
baseContext,
"Authentication failed.",
Toast.LENGTH_SHORT,
).show()
updateUI(null)
}
}
}
Java
mAuth.signInWithCustomToken(mCustomToken)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCustomToken:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCustomToken:failure", task.getException());
Toast.makeText(CustomAuthActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});
로그인이 성공하면 AuthStateListener
에서 getCurrentUser
메서드로 사용자의 계정 데이터를 가져올 수 있습니다.
다음 단계
사용자가 처음으로 로그인하면 신규 사용자 계정이 생성되고 사용자가 로그인할 때 사용한 사용자 인증 정보(사용자 이름과 비밀번호, 전화번호 또는 인증 제공업체 정보)에 연결됩니다. 이 신규 계정은 Firebase 프로젝트의 일부로 저장되며 사용자의 로그인 방법에 관계없이 프로젝트 내 모든 앱에서 사용자를 식별하는 데 사용될 수 있습니다.
인증 제공업체의 사용자 인증 정보를 기존 사용자 계정에 연결하면 사용자가 여러 인증 제공업체를 통해 앱에 로그인할 수 있습니다.
사용자를 로그아웃시키려면 signOut
을 호출합니다.
Kotlin
Firebase.auth.signOut()
Java
FirebaseAuth.getInstance().signOut();
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-08-24(UTC)
[null,null,["최종 업데이트: 2025-08-24(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. If you haven't already, [add Firebase to your Android project](/docs/android/setup).\n2. In your **module (app-level) Gradle file** (usually `\u003cproject\u003e/\u003capp-module\u003e/build.gradle.kts` or `\u003cproject\u003e/\u003capp-module\u003e/build.gradle`), add the dependency for the Firebase Authentication library for Android. We recommend using the [Firebase Android BoM](/docs/android/learn-more#bom) to control library versioning. \n\n ```carbon\n dependencies {\n // Import the BoM for the Firebase platform\n implementation(platform(\"com.google.firebase:firebase-bom:34.1.0\"))\n\n // Add the dependency for the Firebase Authentication library\n // When using the BoM, you don't specify versions in Firebase library dependencies\n implementation(\"com.google.firebase:firebase-auth\")\n }\n ```\n\n By using the [Firebase Android BoM](/docs/android/learn-more#bom),\n your app will always use compatible versions of Firebase Android libraries.\n *(Alternative)*\n Add Firebase library dependencies *without* using the BoM\n\n If you choose not to use the Firebase BoM, you must specify each Firebase library version\n in its dependency line.\n\n **Note that if you use *multiple* Firebase libraries in your app, we strongly\n recommend using the BoM to manage library versions, which ensures that all versions are\n compatible.** \n\n ```groovy\n dependencies {\n // Add the dependency for the Firebase Authentication library\n // When NOT using the BoM, you must specify versions in Firebase library dependencies\n implementation(\"com.google.firebase:firebase-auth:24.0.1\")\n }\n ```\n3. 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\n\n1. In your sign-in activity's `onCreate` method, get the shared instance of the `FirebaseAuth` object: \n\n Kotlin \n\n ```kotlin\n private lateinit var auth: FirebaseAuth\n // ...\n // Initialize Firebase Auth\n auth = Firebase.auth \n https://github.com/firebase/snippets-android/blob/391c1646eacf44d2aab3f76bcfa60dfc6c14acf1/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/CustomAuthActivity.kt#L27-L28\n ```\n\n Java \n\n ```java\n private FirebaseAuth mAuth;\n // ...\n // Initialize Firebase Auth\n mAuth = FirebaseAuth.getInstance();https://github.com/firebase/snippets-android/blob/391c1646eacf44d2aab3f76bcfa60dfc6c14acf1/auth/app/src/main/java/com/google/firebase/quickstart/auth/CustomAuthActivity.java#L48-L49\n ```\n2. When initializing your Activity, check to see if the user is currently signed in: \n\n Kotlin \n\n ```kotlin\n public override fun onStart() {\n super.onStart()\n // Check if user is signed in (non-null) and update UI accordingly.\n val currentUser = auth.currentUser\n updateUI(currentUser)\n }https://github.com/firebase/snippets-android/blob/391c1646eacf44d2aab3f76bcfa60dfc6c14acf1/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/CustomAuthActivity.kt#L33-L38\n ```\n\n Java \n\n ```java\n @Override\n public void onStart() {\n super.onStart();\n // Check if user is signed in (non-null) and update UI accordingly.\n FirebaseUser currentUser = mAuth.getCurrentUser();\n updateUI(currentUser);\n }https://github.com/firebase/snippets-android/blob/391c1646eacf44d2aab3f76bcfa60dfc6c14acf1/auth/app/src/main/java/com/google/firebase/quickstart/auth/CustomAuthActivity.java#L54-L60\n ```\n3. 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.\n4. After you receive the custom token from your authentication server, pass it to `signInWithCustomToken` to sign in the user: \n\n Kotlin \n\n ```kotlin\n customToken?.let {\n auth.signInWithCustomToken(it)\n .addOnCompleteListener(this) { task -\u003e\n if (task.isSuccessful) {\n // Sign in success, update UI with the signed-in user's information\n Log.d(TAG, \"signInWithCustomToken:success\")\n val user = auth.currentUser\n updateUI(user)\n } else {\n // If sign in fails, display a message to the user.\n Log.w(TAG, \"signInWithCustomToken:failure\", task.exception)\n Toast.makeText(\n baseContext,\n \"Authentication failed.\",\n Toast.LENGTH_SHORT,\n ).show()\n updateUI(null)\n }\n }\n }https://github.com/firebase/snippets-android/blob/391c1646eacf44d2aab3f76bcfa60dfc6c14acf1/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/CustomAuthActivity.kt#L44-L63\n ```\n\n Java \n\n ```java\n mAuth.signInWithCustomToken(mCustomToken)\n .addOnCompleteListener(this, new OnCompleteListener\u003cAuthResult\u003e() {\n @Override\n public void onComplete(@NonNull Task\u003cAuthResult\u003e task) {\n if (task.isSuccessful()) {\n // Sign in success, update UI with the signed-in user's information\n Log.d(TAG, \"signInWithCustomToken:success\");\n FirebaseUser user = mAuth.getCurrentUser();\n updateUI(user);\n } else {\n // If sign in fails, display a message to the user.\n Log.w(TAG, \"signInWithCustomToken:failure\", task.getException());\n Toast.makeText(CustomAuthActivity.this, \"Authentication failed.\",\n Toast.LENGTH_SHORT).show();\n updateUI(null);\n }\n }\n });https://github.com/firebase/snippets-android/blob/391c1646eacf44d2aab3f76bcfa60dfc6c14acf1/auth/app/src/main/java/com/google/firebase/quickstart/auth/CustomAuthActivity.java#L65-L82\n ```\n If sign-in succeeds, the `AuthStateListener` you can use the `getCurrentUser` method to get the user's account data.\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 [`FirebaseUser`](/docs/reference/android/com/google/firebase/auth/FirebaseUser) object. See [Manage Users](/docs/auth/android/manage-users).\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/android/account-linking)\n\nTo sign out a user, call [`signOut`](/docs/reference/android/com/google/firebase/auth/FirebaseAuth#signOut()): \n\nKotlin \n\n```kotlin\nFirebase.auth.signOut()https://github.com/firebase/snippets-android/blob/391c1646eacf44d2aab3f76bcfa60dfc6c14acf1/auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/MainActivity.kt#L415-L415\n```\n\nJava \n\n```java\nFirebaseAuth.getInstance().signOut();https://github.com/firebase/snippets-android/blob/391c1646eacf44d2aab3f76bcfa60dfc6c14acf1/auth/app/src/main/java/com/google/firebase/quickstart/auth/MainActivity.java#L501-L501\n```"]]