Naar console

在 Android 上开始使用 Firebase 身份验证

将您的应用关联至 Firebase

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

在项目级层 build.gradle 文件中,请务必在您的 buildscriptallprojects 部分添加 Google 的 Maven 代码库。

将 Firebase 身份验证添加到您的应用中

将 Android 版 Firebase 身份验证库的依赖项添加到您的模块(应用级)Gradle 文件(通常为 app/build.gradle):

implementation 'com.google.firebase:firebase-auth:18.0.0'

要使用身份验证提供方,您需要在 Firebase 控制台中启用它。转到“Firebase 身份验证”部分中的“登录方法”页面,启用电子邮件/密码登录以及您的应用所需的所有其他身份提供方。

检查当前身份验证状态

  1. 声明 FirebaseAuth 的一个实例。

    Java

    private FirebaseAuth mAuth;

    Kotlin

    private lateinit var auth: FirebaseAuth
  2. onCreate() 方法中,初始化 FirebaseAuth 实例。

    Java

    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();

    Kotlin

    // Initialize Firebase Auth
    auth = FirebaseAuth.getInstance()
  3. 初始化您的 Activity 时,请检查用户当前是否已登录。

    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);
    }

    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)
    }

注册新用户

创建一个新的 createAccount 方法,该方法接受电子邮件地址和密码参数,对其进行验证,然后调用 [createUserWithEmailAndPassword](/docs/reference/android/com/google/firebase/auth/FirebaseAuth.html#createUserWithEmailAndPassword(java.lang.String, java.lang.String) 方法创建新用户。

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

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)
            }

            // ...
        }

添加一个表单,以便新用户使用其电子邮件和密码注册,并在提交该表单时调用此新方法。您可以在我们的快速入门示例中查看相关示例。

现有用户登录

创建一个新的 signIn 方法,该方法接受电子邮件地址和密码参数,对这些参数进行验证,然后调用 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

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)
            }

            // ...
        }

添加一个表单,以便用户使用其电子邮件和密码登录,并在提交该表单时调用此新方法。您可以在我们的快速入门示例中查看相关示例。

访问用户信息

如果用户已成功登录,您可以通过 getCurrentUser 方法随时获取他们的帐号数据。

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();
}

Kotlin

val user = FirebaseAuth.getInstance().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
}

后续步骤

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