将您的应用连接到 Firebase
如果您还没有,请将 Firebase 添加到您的 Android 项目中。
将 Firebase 身份验证添加到您的应用
在您的模块(应用级)Gradle 文件(通常为<project>/<app-module>/build.gradle
)中,添加 Firebase 身份验证 Android 库的依赖项。我们建议使用Firebase Android BoM来控制库版本。 Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.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-ktx' }
通过使用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-ktx:21.1.0' }
Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.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:21.1.0' }
要使用身份验证提供程序,您需要在Firebase 控制台中启用它。转到 Firebase 身份验证部分中的登录方法页面,为您的应用启用电子邮件/密码登录和任何其他身份提供商。
(可选)使用 Firebase Local Emulator Suite 制作原型并进行测试
在讨论您的应用程序如何对用户进行身份验证之前,让我们先介绍一组可用于制作原型和测试身份验证功能的工具:Firebase Local Emulator Suite。如果您要在身份验证技术和提供者之间做出决定,使用身份验证和 Firebase 安全规则尝试使用公共和私有数据的不同数据模型,或者对登录 UI 设计进行原型设计,那么能够在不部署实时服务的情况下在本地工作可能是个好主意.
身份验证模拟器是本地模拟器套件的一部分,它使您的应用程序能够与模拟的数据库内容和配置以及可选的模拟项目资源(函数、其他数据库和安全规则)进行交互。
使用 Authentication 模拟器只需要几个步骤:
- 在您的应用程序的测试配置中添加一行代码以连接到模拟器。
- 从本地项目目录的根目录运行
firebase emulators:start
。 - 使用本地模拟器套件 UI 进行交互式原型设计,或使用身份验证模拟器 REST API 进行非交互式测试。
详细指南可在将您的应用程序连接到身份验证模拟器中找到。有关详细信息,请参阅Local Emulator Suite 介绍。
现在让我们继续介绍如何对用户进行身份验证。
检查当前授权状态
声明
FirebaseAuth
的一个实例。Kotlin+KTX
private lateinit var auth: FirebaseAuth
Java
private FirebaseAuth mAuth;
在
onCreate()
方法中,初始化FirebaseAuth
实例。Kotlin+KTX
// Initialize Firebase Auth auth = Firebase.auth
Java
// Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
初始化 Activity 时,检查用户当前是否已登录。
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(); } }
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(); } }
注册新用户
创建一个新的createAccount
方法,接收电子邮件地址和密码,验证它们,然后使用createUserWithEmailAndPassword
方法创建一个新用户。
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) } }
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); } } });
添加一个表单以使用他们的电子邮件和密码注册新用户,并在提交时调用这个新方法。您可以在我们的快速入门示例中看到一个示例。
登录现有用户
创建一个新的登录方法,它接收电子邮件地址和密码,验证它们,然后使用signIn
方法signInWithEmailAndPassword
用户。
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) } }
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); } } });
添加一个表单以使用用户的电子邮件和密码登录用户,并在提交时调用此新方法。您可以在我们的快速入门示例中看到一个示例。
访问用户信息
如果用户已成功登录,您可以随时使用getCurrentUser
方法获取他们的帐户数据。
Kotlin+KTX
val user = Firebase.auth.currentUser user?.let { // Name, email address, and profile photo Url val name = user.displayName val email = user.email val photoUrl = user.photoUrl // Check if user's email is verified val emailVerified = user.isEmailVerified // The user's ID, unique to the Firebase project. Do NOT use this value to // authenticate with your backend server, if you have one. Use // FirebaseUser.getToken() instead. val uid = user.uid }
Java
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { // Name, email address, and profile photo Url String name = user.getDisplayName(); String email = user.getEmail(); Uri photoUrl = user.getPhotoUrl(); // Check if user's email is verified boolean emailVerified = user.isEmailVerified(); // The user's ID, unique to the Firebase project. Do NOT use this value to // authenticate with your backend server, if you have one. Use // FirebaseUser.getIdToken() instead. String uid = user.getUid(); }
下一步
浏览有关添加其他身份和身份验证服务的指南: