Join us for Firebase Summit on November 10, 2021. Tune in to learn how Firebase can help you accelerate app development, release with confidence, and scale with ease. Register

在 Firebase 中管理用戶

創建用戶

您可以通過調用創建你的火力地堡項目中的新用戶createUserWithEmailAndPassword方法或者通過聯合身份提供者,如在首次用戶登錄谷歌登錄的帳戶Facebook的登錄

您也可以從的身份驗證部分創建新密碼驗證的用戶火力地堡控制台,用戶頁面上的。

獲取當前登錄的用戶

推薦的方式來獲得當前用戶是通過調用getCurrentUser方法。如果沒有用戶登錄, getCurrentUser返回null:

爪哇

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

科特林+KTX

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

有些情況下, getCurrentUser將返回一個非空FirebaseUser但潛在的令牌無效。例如,如果用戶在另一台設備上被刪除並且本地令牌沒有刷新,就會發生這種情況。在這種情況下,你可能會得到一個有效的用戶getCurrentUser但隨後經過身份驗證的資源調用都將失敗。

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

如果您安裝AuthStateListener你每次都會底層令牌狀態的變化得到一個回調。這對於對上面提到的邊緣情況做出反應非常有用。

獲取用戶的個人資料

要獲得用戶的個人資料信息,使用實例的存取方法FirebaseUser 。例如:

爪哇

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

科特林+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方法。例如:

爪哇

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

科特林+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方法。例如:

爪哇

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

科特林+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方法。例如:

爪哇

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

科特林+KTX

val user = Firebase.auth.currentUser

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

向用戶發送驗證電子郵件

您可以發送一個地址驗證電子郵件與用戶sendEmailVerification方法。例如:

爪哇

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

科特林+KTX

val user = Firebase.auth.currentUser

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

您可以自定義在認證部分中使用的電子郵件模板火力地堡控制台,電子郵件模板頁面上。參見電子郵件模板在火力地堡幫助中心。

也可以通過國家通過繼續URL後面發送驗證電子郵件時重定向到應用程序。

此外,您可以通過在發送電子郵件之前更新 Auth 實例上的語言代碼來本地化驗證電子郵件。例如:

爪哇

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

科特林+KTX

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

設置用戶密碼

您可以設置用戶與密碼updatePassword方法。例如:

爪哇

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

科特林+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方法。例如:

爪哇

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

科特林+KTX

val emailAddress = "user@example.com"

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

您可以自定義在認證部分中使用的電子郵件模板火力地堡控制台,電子郵件模板頁面上。參見電子郵件模板在火力地堡幫助中心。

也可以通過國家通過繼續URL後面發送密碼重置郵件時重定向到應用程序。

此外,您可以通過在發送電子郵件之前更新 Auth 實例上的語言代碼來本地化密碼重置電子郵件。例如:

爪哇

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

科特林+KTX

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

您還可以從 Firebase 控制台發送密碼重置電子郵件。

刪除用戶

您可以使用刪除用戶帳戶delete方法。例如:

爪哇

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

科特林+KTX

val user = Firebase.auth.currentUser!!

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

您也可以刪除用戶從的身份驗證部分火力地堡控制台,用戶頁面上的。

重新驗證用戶

一些安全敏感的操作,如刪除帳戶設置一個主電子郵件地址,並更改密碼-require用戶已在近期簽署。如果執行這些操作之一,而且用戶在太長簽署前,行動失敗並引發FirebaseAuthRecentLoginRequiredException 。發生這種情況時,通過獲取新的登錄用戶提供憑據並傳遞憑據重新驗證用戶reauthenticate 。例如:

爪哇

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

科特林+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.") }

導入用戶帳戶

您可以從文件中使用火力地堡CLI的用戶帳戶導入您的火力地堡項目auth:import命令。例如:

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