Tạo người dùng
Bạn tạo người dùng mới trong dự án Firebase bằng cách gọi phương thức createUserWithEmailAndPassword
hoặc bằng cách đăng nhập người dùng lần đầu tiên thông qua nhà cung cấp danh tính được liên kết, chẳng hạn như Đăng nhập bằng Google hoặc Đăng nhập Facebook.
Bạn cũng có thể tạo người dùng mới được xác thực mật khẩu từ mục Xác thực trong bảng điều khiển của Firebase, trên trang Người dùng.
Tải người dùng hiện đang đăng nhập
Bạn nên gọi phương thức getCurrentUser
để lấy người dùng hiện tại.
Nếu không có người dùng nào đăng nhập, getCurrentUser
sẽ trả về giá trị rỗng:
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 }
Có một số trường hợp trong đó getCurrentUser
sẽ trả về một FirebaseUser
khác rỗng nhưng mã thông báo cơ bản lại không hợp lệ. Điều này có thể xảy ra, chẳng hạn như khi người dùng đã bị xoá trên một thiết bị khác và mã thông báo cục bộ chưa được làm mới. Trong trường hợp này, bạn có thể nhận được một getCurrentUser
người dùng hợp lệ nhưng các lệnh gọi tiếp theo đến tài nguyên đã xác thực sẽ không thực hiện được.
getCurrentUser
cũng có thể trả về null
vì đối tượng xác thực chưa khởi chạy xong.
Nếu đính kèm AuthStateListener, bạn sẽ nhận được lệnh gọi lại mỗi khi trạng thái của mã thông báo cơ bản thay đổi. Điều này có thể hữu ích để phản ứng với các trường hợp hiếm gặp như những trường hợp đã đề cập ở trên.
Lấy hồ sơ của người dùng
Để lấy thông tin hồ sơ của người dùng, hãy sử dụng các phương thức truy cập của một thực thể của FirebaseUser
. Ví dụ:
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(); }
Lấy thông tin hồ sơ theo nhà cung cấp cụ thể của người dùng
Để lấy thông tin hồ sơ từ các trình cung cấp dịch vụ đăng nhập được liên kết với người dùng, hãy sử dụng phương thức getProviderData
. Ví dụ:
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(); } }
Cập nhật hồ sơ của người dùng
Bạn có thể cập nhật thông tin hồ sơ cơ bản của người dùng (tên hiển thị và URL ảnh hồ sơ của người dùng) bằng phương thức updateProfile
. Ví dụ:
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."); } } });
Đặt địa chỉ email của người dùng
Bạn có thể thiết lập địa chỉ email của người dùng bằng phương thức updateEmail
. Ví dụ:
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."); } } });
Gửi email xác minh cho người dùng
Bạn có thể gửi email xác minh địa chỉ cho người dùng bằng phương thức
sendEmailVerification
. Ví dụ:
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."); } } });
Bạn có thể tuỳ chỉnh mẫu email được dùng trong phần Xác thực của bảng điều khiển Firebase, trên trang Mẫu email. Hãy xem phần Mẫu email trong Trung tâm trợ giúp của Firebase.
Bạn cũng có thể chuyển trạng thái thông qua URL tiếp tục để chuyển hướng trở lại ứng dụng khi gửi email xác minh.
Ngoài ra, bạn có thể bản địa hoá email xác minh bằng cách cập nhật mã ngôn ngữ trên thực thể Xác thực trước khi gửi email. Ví dụ:
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();
Đặt mật khẩu của người dùng
Bạn có thể đặt mật khẩu của người dùng bằng phương thức updatePassword
. Ví dụ:
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."); } } });
Gửi email đặt lại mật khẩu
Bạn có thể gửi email đặt lại mật khẩu cho người dùng bằng phương thức sendPasswordResetEmail
. Ví dụ:
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."); } } });
Bạn có thể tuỳ chỉnh mẫu email được dùng trong phần Xác thực của bảng điều khiển Firebase, trên trang Mẫu email. Hãy xem phần Mẫu email trong Trung tâm trợ giúp của Firebase.
Bạn cũng có thể chuyển trạng thái thông qua URL tiếp tục để chuyển hướng trở lại ứng dụng khi gửi email đặt lại mật khẩu.
Ngoài ra, bạn có thể bản địa hoá email đặt lại mật khẩu bằng cách cập nhật mã ngôn ngữ trên thực thể Xác thực trước khi gửi email. Ví dụ:
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();
Bạn cũng có thể gửi email đặt lại mật khẩu từ bảng điều khiển của Firebase.
Xóa người dùng
Bạn có thể xoá tài khoản người dùng bằng phương thức delete
. Ví dụ:
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."); } } });
Bạn cũng có thể xóa người dùng khỏi phần Xác thực của bảng điều khiển Firebase, trên trang Người dùng.
Xác thực lại người dùng
Một số thao tác nhạy cảm về bảo mật (chẳng hạn như xoá tài khoản, đặt địa chỉ email chính và đổi mật khẩu) đòi hỏi người dùng phải đăng nhập gần đây. Nếu bạn thực hiện một trong những thao tác này và người dùng đã đăng nhập cách đây quá lâu, thì thao tác đó sẽ không thành công và gửi FirebaseAuthRecentLoginRequiredException
.
Khi điều này xảy ra, hãy xác thực lại người dùng bằng cách nhận thông tin đăng nhập mới từ người dùng và chuyển thông tin đăng nhập tới reauthenticate
. Ví dụ:
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."); } });
Nhập tài khoản người dùng
Bạn có thể nhập tài khoản người dùng từ một tệp vào dự án Firebase bằng cách sử dụng lệnh auth:import
của Firebase CLI. Ví dụ:
firebase auth:import users.json --hash-algo=scrypt --rounds=8 --mem-cost=14