借助 Firebase Authentication,您可以让您的用户使用其电子邮件地址和密码进行 Firebase 身份验证,还可以管理您的应用的基于密码的帐号。
准备工作
将 Firebase 添加到您的 Android 项目(如果尚未添加)。
- 如果您尚未将应用关联至您的 Firebase 项目,请从 Firebase 控制台执行此操作。
- 启用“电子邮件地址/密码”登录机制:
- 在 Firebase 控制台中,打开身份验证部分。
- 在登录方法标签页中,启用电子邮件地址/密码登录方法,然后点击保存。
使用 Firebase Android BoM 在模块(应用级)Gradle 文件(通常为
app/build.gradle
)中声明 Firebase Authentication Android 库的依赖项。Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.8.0') // Declare 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 { // Declare 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:20.0.3' }
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.8.0') // Declare 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-ktx' }
使用 Firebase Android BoM,可确保您的应用始终使用 Firebase Android 库的兼容版本。
(替代方法) 在不使用 BoM 的情况下声明 Firebase 库依赖项
如果您选择不使用 Firebase BoM,则必须在其依赖项行中指定每个 Firebase 库版本。
请注意,如果您在应用中使用多个 Firebase 库,我们强烈建议您使用 BoM 来管理库版本,以确保所有版本都兼容。
dependencies { // Declare 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-ktx:20.0.3' }
创建一个基于密码的帐号
如需创建一个带有密码的新用户帐号,请在您应用的登录 Activity 中完成以下步骤:
- 在登录 Activity 的
onCreate
方法中,获取FirebaseAuth
对象的共享实例:Java
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
Kotlin+KTX
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
- 初始化您的 Activity 时,检查用户当前是否已登录:
Java
@Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); if(currentUser != null){ reload(); } }
Kotlin+KTX
public override fun onStart() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. val currentUser = auth.currentUser if(currentUser != null){ reload(); } }
- 当新用户使用您的应用注册表单注册时,完成您的应用需要的所有新帐号验证步骤,例如验证新帐号的密码是否输入正确并且符合您的密码复杂度要求。
- 将新用户的电子邮件地址和密码传递给
createUserWithEmailAndPassword
方法,创建一个新帐号:Java
mAuth.createUserWithEmailAndPassword(email, password) .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, "createUserWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { // If sign in fails, display a message to the user. Log.w(TAG, "createUserWithEmail:failure", task.getException()); Toast.makeText(EmailPasswordActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); updateUI(null); } } });
Kotlin+KTX
auth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "createUserWithEmail:success") val user = auth.currentUser updateUI(user) } else { // If sign in fails, display a message to the user. Log.w(TAG, "createUserWithEmail:failure", task.exception) Toast.makeText(baseContext, "Authentication failed.", Toast.LENGTH_SHORT).show() updateUI(null) } }
getCurrentUser
方法来获取用户的帐号数据。
使用电子邮件地址和密码登录用户
使用密码让用户登录的步骤与创建新帐号的步骤类似。在您应用的登录 Activity 中,执行以下操作:
- 在登录 Activity 的
onCreate
方法中,获取FirebaseAuth
对象的共享实例:Java
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
Kotlin+KTX
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
- 初始化您的 Activity 时,检查用户当前是否已登录:
Java
@Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); if(currentUser != null){ reload(); } }
Kotlin+KTX
public override fun onStart() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. val currentUser = auth.currentUser if(currentUser != null){ reload(); } }
- 当用户登录到您的应用时,将该用户的电子邮件地址和密码传递给
signInWithEmailAndPassword
:Java
mAuth.signInWithEmailAndPassword(email, password) .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, "signInWithEmail:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithEmail:failure", task.getException()); Toast.makeText(EmailPasswordActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); updateUI(null); } } });
Kotlin+KTX
auth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithEmail:success") val user = auth.currentUser updateUI(user) } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithEmail:failure", task.exception) Toast.makeText(baseContext, "Authentication failed.", Toast.LENGTH_SHORT).show() updateUI(null) } }
FirebaseUser
继续操作。
后续步骤
在用户首次登录后,系统会创建一个新的用户帐号,并将其与该用户登录时使用的凭据(即用户名和密码、电话号码或者身份验证提供方信息)相关联。此新帐号存储在您的 Firebase 项目中,无论用户采用何种方式登录,您项目中的每个应用都可以使用此帐号来识别用户。
-
在您的应用中,您可以从
FirebaseUser
对象中获取用户的基本个人资料信息。请参阅管理用户。 在您的 Firebase Realtime Database 和 Cloud Storage 安全规则中,您可以从
auth
变量获取已登录用户的唯一用户 ID,然后利用此 ID 来控制用户可以访问哪些数据。
您可以通过将身份验证提供方凭据关联至现有用户帐号,让用户可以使用多个身份验证提供方登录您的应用。
如需将用户退出登录,请调用 signOut
:
Java
FirebaseAuth.getInstance().signOut();
Kotlin+KTX
Firebase.auth.signOut()