获取我们在 Firebase 峰会上发布的所有信息,了解 Firebase 可如何帮助您加快应用开发速度并满怀信心地运行应用。了解详情

在 Firebase 中管理用户

使用集合让一切井井有条 根据您的偏好保存内容并对其进行分类。

创建用户

您可以通过调用createUserWithEmailAndPassword方法或使用联合身份提供商(例如Google Sign-InFacebook Login )首次登录用户来在 Firebase 项目中创建新用户。

您还可以在Firebase 控制台的“用户”页面上的“身份验证”部分创建新的经过密码身份验证的用户。

获取当前登录的用户

获取当前用户的推荐方法是调用getCurrentUser方法。如果没有用户登录, getCurrentUser将返回 null:

Java

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // User is signed in
} else {
    // No user is signed in
}

Kotlin+KTX

val user = Firebase.auth.currentUser
if (user != null) {
    // User is signed in
} else {
    // No user is signed in
}

在某些情况下, getCurrentUser将返回非 null FirebaseUser ,但基础令牌无效。例如,如果用户在另一台设备上被删除并且本地令牌尚未刷新,则可能会发生这种情况。在这种情况下,您可能会获得一个有效的用户getCurrentUser ,但随后对经过身份验证的资源的调用将失败。

getCurrentUser也可能返回null ,因为 auth 对象尚未完成初始化。

如果您附加一个AuthStateListener ,您将在每次底层令牌状态更改时收到一个回调。这对于对上述边缘情况做出反应很有用。

获取用户的个人资料

要获取用户的个人资料信息,请使用FirebaseUser实例的访问器方法。例如:

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

获取用户的提供商特定的个人资料信息

要获取从链接到用户的登录提供程序检索的配置文件信息,请使用getProviderData方法。例如:

Java

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    for (UserInfo profile : user.getProviderData()) {
        // Id of the provider (ex: google.com)
        String providerId = profile.getProviderId();

        // UID specific to the provider
        String uid = profile.getUid();

        // Name, email address, and profile photo Url
        String name = profile.getDisplayName();
        String email = profile.getEmail();
        Uri photoUrl = profile.getPhotoUrl();
    }
}

Kotlin+KTX

val user = Firebase.auth.currentUser
user?.let {
    for (profile in it.providerData) {
        // Id of the provider (ex: google.com)
        val providerId = profile.providerId

        // UID specific to the provider
        val uid = profile.uid

        // Name, email address, and profile photo Url
        val name = profile.displayName
        val email = profile.email
        val photoUrl = profile.photoUrl
    }
}

更新用户的个人资料

您可以使用updateProfile方法更新用户的基本个人资料信息(用户的显示名称和个人资料照片 URL)。例如:

Java

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
        .setDisplayName("Jane Q. User")
        .setPhotoUri(Uri.parse("https://example.com/jane-q-user/profile.jpg"))
        .build();

user.updateProfile(profileUpdates)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "User profile updated.");
                }
            }
        });

Kotlin+KTX

val user = Firebase.auth.currentUser

val profileUpdates = userProfileChangeRequest {
    displayName = "Jane Q. User"
    photoUri = Uri.parse("https://example.com/jane-q-user/profile.jpg")
}

user!!.updateProfile(profileUpdates)
        .addOnCompleteListener { task ->
            if (task.isSuccessful) {
                Log.d(TAG, "User profile updated.")
            }
        }

设置用户的电子邮件地址

您可以使用updateEmail方法设置用户的电子邮件地址。例如:

Java

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

user.updateEmail("user@example.com")
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "User email address updated.");
                }
            }
        });

Kotlin+KTX

val user = Firebase.auth.currentUser

user!!.updateEmail("user@example.com")
        .addOnCompleteListener { task ->
            if (task.isSuccessful) {
                Log.d(TAG, "User email address updated.")
            }
        }

向用户发送验证电子邮件

您可以使用sendEmailVerification方法向用户发送地址验证电子邮件。例如:

Java

FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();

user.sendEmailVerification()
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "Email sent.");
                }
            }
        });

Kotlin+KTX

val user = Firebase.auth.currentUser

user!!.sendEmailVerification()
        .addOnCompleteListener { task ->
            if (task.isSuccessful) {
                Log.d(TAG, "Email sent.")
            }
        }

您可以在电子邮件模板页面上自定义Firebase 控制台的身份验证部分中使用的电子邮件模板。请参阅 Firebase 帮助中心的电子邮件模板

发送验证电子邮件时,也可以通过继续 URL传递状态以重定向回应用程序。

此外,您可以通过在发送电子邮件之前更新 Auth 实例上的语言代码来本地化验证电子邮件。例如:

Java

auth.setLanguageCode("fr");
// To apply the default app language instead of explicitly setting it.
// auth.useAppLanguage();

Kotlin+KTX

auth.setLanguageCode("fr")
// To apply the default app language instead of explicitly setting it.
// auth.useAppLanguage()

设置用户密码

您可以使用updatePassword方法设置用户的密码。例如:

Java

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String newPassword = "SOME-SECURE-PASSWORD";

user.updatePassword(newPassword)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "User password updated.");
                }
            }
        });

Kotlin+KTX

val user = Firebase.auth.currentUser
val newPassword = "SOME-SECURE-PASSWORD"

user!!.updatePassword(newPassword)
        .addOnCompleteListener { task ->
            if (task.isSuccessful) {
                Log.d(TAG, "User password updated.")
            }
        }

发送密码重置电子邮件

您可以使用sendPasswordResetEmail方法向用户发送密码重置电子邮件。例如:

Java

FirebaseAuth auth = FirebaseAuth.getInstance();
String emailAddress = "user@example.com";

auth.sendPasswordResetEmail(emailAddress)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "Email sent.");
                }
            }
        });

Kotlin+KTX

val emailAddress = "user@example.com"

Firebase.auth.sendPasswordResetEmail(emailAddress)
        .addOnCompleteListener { task ->
            if (task.isSuccessful) {
                Log.d(TAG, "Email sent.")
            }
        }

您可以在电子邮件模板页面上自定义Firebase 控制台的身份验证部分中使用的电子邮件模板。请参阅 Firebase 帮助中心的电子邮件模板

发送密码重置电子邮件时,还可以通过继续 URL传递状态以重定向回应用程序。

此外,您可以通过在发送电子邮件之前更新 Auth 实例上的语言代码来本地化密码重置电子邮件。例如:

Java

auth.setLanguageCode("fr");
// To apply the default app language instead of explicitly setting it.
// auth.useAppLanguage();

Kotlin+KTX

auth.setLanguageCode("fr")
// To apply the default app language instead of explicitly setting it.
// auth.useAppLanguage()

您还可以从 Firebase 控制台发送密码重置电子邮件。

删除用户

您可以使用delete方法删除用户帐户。例如:

Java

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

user.delete()
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
                    Log.d(TAG, "User account deleted.");
                }
            }
        });

Kotlin+KTX

val user = Firebase.auth.currentUser!!

user.delete()
        .addOnCompleteListener { task ->
            if (task.isSuccessful) {
                Log.d(TAG, "User account deleted.")
            }
        }

您还可以在Firebase 控制台的“用户”页面上的“身份验证”部分删除用户。

重新验证用户

某些安全敏感操作(例如删除帐户设置主电子邮件地址更改密码)要求用户最近登录。如果您执行这些操作之一,而用户登录时间过长,则操作失败并抛出FirebaseAuthRecentLoginRequiredException 。发生这种情况时,通过从用户获取新的登录凭据并将凭据传递给reauthenticate来重新验证用户。例如:

Java

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

// Get auth credentials from the user for re-authentication. The example below shows
// email and password credentials but there are multiple possible providers,
// such as GoogleAuthProvider or FacebookAuthProvider.
AuthCredential credential = EmailAuthProvider
        .getCredential("user@example.com", "password1234");

// Prompt the user to re-provide their sign-in credentials
user.reauthenticate(credential)
        .addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                Log.d(TAG, "User re-authenticated.");
            }
        });

Kotlin+KTX

val user = Firebase.auth.currentUser!!

// Get auth credentials from the user for re-authentication. The example below shows
// email and password credentials but there are multiple possible providers,
// such as GoogleAuthProvider or FacebookAuthProvider.
val credential = EmailAuthProvider
        .getCredential("user@example.com", "password1234")

// Prompt the user to re-provide their sign-in credentials
user.reauthenticate(credential)
        .addOnCompleteListener { Log.d(TAG, "User re-authenticated.") }

导入用户帐户

您可以使用 Firebase CLI 的auth:import命令将用户帐户从文件导入您的 Firebase 项目。例如:

firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14