Firebase Authentication 使用入门 (Android)

将您的应用关联至 Firebase

将 Firebase 添加到您的 Android 项目(如果尚未添加)。

将 Firebase Authentication 添加到您的应用

在您的模块(应用级)Gradle 文件(通常是 <project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle)中,添加 Firebase Authentication Android 库的依赖项。我们建议使用 Firebase Android BoM 来实现库版本控制。

Kotlin+KTX

dependencies {
    // Import the BoM for the Firebase platform
    implementation(platform("com.google.firebase:firebase-bom:32.3.1"))

    // 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:22.1.2")
}

Java

dependencies {
    // Import the BoM for the Firebase platform
    implementation(platform("com.google.firebase:firebase-bom:32.3.1"))

    // 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:22.1.2")
}

如需使用身份验证提供方,您需要在 Firebase 控制台中启用该提供方。浏览到“Firebase Authentication”部分中的“Sign-in Method”(登录方法)页面,启用电子邮件地址/密码登录以及您的应用所需的所有其他身份提供方。

(可选)使用 Firebase Local Emulator Suite 进行原型设计和测试

在介绍应用如何对用户进行身份验证之前,我们先介绍一套可用于对 Authentication 功能进行原型设计和测试的工具,即 Firebase Local Emulator Suite。如果您正要从几种身份验证方法和数个提供方中做出选择、对使用 Authentication 和 Firebase 安全规则的公共和私有数据尝试不同的数据模型,或者想要对登录界面进行原型设计,那么无需实际部署即可在本地进行上述工作是非常理想的。

Authentication 模拟器是 Local Emulator Suite 的一部分,可让您的应用与模拟的数据库内容和配置进行交互,以及视需要与您的模拟项目资源(函数、其他数据库和安全规则)进行交互。

如需使用 Authentication 模拟器,只需完成几个步骤:

  1. 向应用的测试配置添加一行代码以连接到模拟器。
  2. 从本地项目的根目录运行 firebase emulators:start
  3. 使用 Local Emulator Suite 界面进行交互式原型设计,或使用 Authentication 模拟器 REST API 进行非交互式测试。

如需查看详细指南,请参阅将您的应用连接到 Authentication 模拟器。如需了解详情,请参阅 Local Emulator Suite 简介

接下来,我们来看看如何对用户进行身份验证。

检查当前身份验证状态

  1. 声明 FirebaseAuth 的一个实例。

    Kotlin+KTX

    private lateinit var auth: FirebaseAuth

    Java

    private FirebaseAuth mAuth;
  2. onCreate() 方法中,初始化 FirebaseAuth 实例。

    Kotlin+KTX

    // Initialize Firebase Auth
    auth = Firebase.auth

    Java

    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
  3. 初始化 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 = it.displayName
    val email = it.email
    val photoUrl = it.photoUrl

    // Check if user's email is verified
    val emailVerified = it.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.
    val uid = it.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();
}

后续步骤

浏览有关添加其他身份和身份验证服务的指南: