使用自定义身份验证系统进行 Firebase 身份验证 (Android)
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
您可以通过修改身份验证服务器,在用户成功登录时生成自定义的签名令牌,将 Firebase Authentication 与自定义身份验证系统集成。您的应用会接收此令牌并将其用于 Firebase 身份验证。
准备工作
- 将 Firebase 添加到您的 Android 项目(如果尚未添加)。
-
在模块(应用级)Gradle 文件(通常是
<project>/<app-module>/build.gradle.kts
或 <project>/<app-module>/build.gradle
)中,添加 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 身份验证
- 在登录 Activity 的
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();
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-21。
[null,null,["最后更新时间 (UTC):2025-08-21。"],[],[],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```"]]