在 Firebase 中管理用户

创建用户

如需在 Firebase 项目中创建新用户,您可以调用 createUserWithEmailAndPassword 方法,或让用户通过 Google 登录服务或 Facebook 登录服务等联合身份提供方服务完成首次登录。

您还可以转至 Firebase 控制台的“Authentication”部分,在“用户”页面中创建以密码验证身份的新用户。

获取当前登录的用户

要获取当前用户,建议调用 getCurrentUser 方法。如果没有登录的用户,getCurrentUser 会返回 null:

Kotlin+KTX

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

Java

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

在某些情况下,getCurrentUser 将返回一个非空 FirebaseUser,但底层令牌无效。例如,如果用户在其他设备上被删除,而本地令牌尚未刷新,即可能发生此情况。在这种情况下,您可能会获得一个有效的用户 getCurrentUser,但对已通过身份验证的资源的后续调用将失败。

如果 auth 对象尚未完成初始化,则 getCurrentUser 也有可能返回 null

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

获取用户个人资料

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

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

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

要获取从用户已关联的登录服务提供方检索到的个人资料信息,可使用 getProviderData 方法。例如:

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

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

更新用户个人资料

您可以使用 updateProfile 方法来更新用户的基本个人资料信息,即用户的显示名称和个人资料照片网址。例如:

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

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

设置用户电子邮件地址

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

Kotlin+KTX

val user = Firebase.auth.currentUser

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

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

向用户发送验证电子邮件

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

Kotlin+KTX

val user = Firebase.auth.currentUser

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

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

您可以在 Firebase 控制台的“Authentication”部分的“电子邮件模板”页面中自定义使用的电子邮件模板。请参阅 Firebase 帮助中心内的电子邮件模板

在发送验证电子邮件时,还可以通过一个接续网址传递状态以重定向回应用。

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

Kotlin+KTX

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

Java

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

设置用户密码

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

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

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

发送重设密码电子邮件

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

Kotlin+KTX

val emailAddress = "user@example.com"

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

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

您可以在 Firebase 控制台的“Authentication”部分的“电子邮件模板”页面中自定义使用的电子邮件模板。请参阅 Firebase 帮助中心内的电子邮件模板

在发送重设密码电子邮件时,还可以通过一个接续网址传递状态以重定向回应用。

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

Kotlin+KTX

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

Java

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

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

删除用户

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

Kotlin+KTX

val user = Firebase.auth.currentUser!!

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

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

您还可以前往 Firebase 控制台的“Authentication”部分,在“用户”页面中删除用户。

重新对用户进行身份验证

某些涉及安全的敏感操作(例如删除帐号设置主电子邮件地址更改密码)只能针对最近登录过的用户执行。如果您执行某项这类操作,而该用户的登录时间已经是很久之前,该操作便会失败并抛出 FirebaseAuthRecentLoginRequiredException。发生这种情况时,请向用户索取新的登录凭据并将这些凭据传递给 reauthenticate,以便对该用户重新进行身份验证。例如:

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

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

导入用户帐号

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

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