使用自訂驗證系統在 Android 上透過 Firebase 進行驗證
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
您可以修改驗證伺服器,在使用者成功登入時產生自訂簽署的權杖,藉此將 Firebase Authentication 與自訂驗證系統整合。應用程式會收到這個權杖,並用來向 Firebase 進行驗證。
事前準備
- 如果您尚未將 Firebase 新增至 Android 專案,請先新增。
-
在模組 (應用程式層級) Gradle 檔案 (通常是
<project>/<app-module>/build.gradle.kts
或 <project>/<app-module>/build.gradle
) 中,加入 Android 適用的 Firebase Authentication 程式庫依附元件。建議使用 Firebase Android BoM 控制程式庫版本。
<0xdependencies {
// 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();
- 初始化 Activity 時,請檢查使用者目前是否已登入:
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();
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-21 (世界標準時間)。
[null,null,["上次更新時間:2025-08-21 (世界標準時間)。"],[],[],null,["# Authenticate with Firebase on Android Using a Custom Authentication System\n\nYou 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----------------\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--------------------------\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----------\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\n### Kotlin\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\n### Java\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```"]]