Kết nối ứng dụng với Firebase
Nếu bạn chưa thực hiện, hãy thêm Firebase vào dự án Android.
Thêm Firebase Authentication vào ứng dụng
Trong tệp Gradle của mô-đun (cấp ứng dụng) (thường là
<project>/<app-module>/build.gradle.ktshoặc<project>/<app-module>/build.gradle), hãy thêm phần phụ thuộc của thư viện Firebase Authentication cho Android. Bạn nên sử dụng Firebase Android BoM để kiểm soát việc quản lý phiên bản thư viện.dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.15.0")) // Add the dependency for the Firebase Authentication library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-auth") }
Bằng cách sử dụng Firebase Android BoM, ứng dụng của bạn sẽ luôn sử dụng những phiên bản tương thích của thư viện Android trên Firebase.
(Giải pháp thay thế) Thêm phần phụ thuộc của thư viện Firebase mà không sử dụng BoM
Nếu chọn không sử dụng Firebase BoM, bạn phải chỉ định từng phiên bản thư viện Firebase trong dòng phần phụ thuộc.
Xin lưu ý rằng nếu bạn sử dụng nhiều thư viện Firebase trong ứng dụng, bạn nên sử dụng BoM để quản lý các phiên bản thư viện nhằm đảm bảo rằng tất cả các phiên bản đều tương thích.
dependencies { // Add the dependency for the Firebase Authentication library // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-auth:24.1.0") }
Để sử dụng nhà cung cấp dịch vụ xác thực, bạn cần bật nhà cung cấp đó trong bảng điều khiển Firebase Firebase. Chuyển đến trang Phương thức đăng nhập trong phần Firebase Authentication để bật tính năng đăng nhập bằng email/mật khẩu và mọi nhà cung cấp danh tính khác mà bạn muốn dùng cho ứng dụng.
(Không bắt buộc) Tạo nguyên mẫu và kiểm thử bằng Firebase Local Emulator Suite
Trước khi nói về cách ứng dụng xác thực người dùng, hãy cùng tìm hiểu một bộ công cụ mà bạn có thể dùng để tạo nguyên mẫu và kiểm thử Authentication chức năng: Firebase Local Emulator Suite. Nếu bạn đang cân nhắc giữa các kỹ thuật xác thực và nhà cung cấp dịch vụ, thử các mô hình dữ liệu khác nhau với dữ liệu công khai và riêng tư bằng cách sử dụng Authentication và Firebase Security Rules, hoặc tạo nguyên mẫu thiết kế giao diện người dùng đăng nhập, thì việc có thể làm việc cục bộ mà không cần triển khai các dịch vụ trực tiếp có thể là một ý tưởng hay.
Trình mô phỏng Authentication là một phần của Local Emulator Suite, cho phép ứng dụng của bạn tương tác với nội dung và cấu hình cơ sở dữ liệu được mô phỏng, cũng như các tài nguyên dự án được mô phỏng (các hàm, cơ sở dữ liệu khác và quy tắc bảo mật) (không bắt buộc).
Việc sử dụng trình mô phỏng Authentication chỉ bao gồm một vài bước:
- Thêm một dòng mã vào cấu hình kiểm thử của ứng dụng để kết nối với trình mô phỏng.
- Chạy
firebase emulators:starttừ thư mục gốc của dự án cục bộ. - Sử dụng giao diện người dùng Local Emulator Suite để tạo nguyên mẫu tương tác hoặc API REST của trình mô phỏng Authentication để kiểm thử không tương tác.
Bạn có thể xem hướng dẫn chi tiết tại bài viết Kết nối ứng dụng với trình mô phỏng Authentication. Để biết thêm thông tin, hãy xem bài viết Local Emulator Suite giới thiệu.
Bây giờ, hãy tiếp tục tìm hiểu cách xác thực người dùng.
Kiểm tra trạng thái xác thực hiện tại
Khai báo một thực thể của
FirebaseAuth.Kotlin
private lateinit var auth: FirebaseAuth
Java
private FirebaseAuth mAuth;
Trong phương thức
onCreate(), hãy khởi chạy thực thểFirebaseAuth.Kotlin
// Initialize Firebase Auth auth = Firebase.auth
Java
// Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
Khi khởi chạy Hoạt động, hãy kiểm tra xem người dùng có đang đăng nhập hay không.
Kotlin
public override fun onStart() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. val currentUser = auth.currentUser if (currentUser != null) { reload() } }
Java
@Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); if(currentUser != null){ reload(); } }
Đăng ký người dùng mới
Tạo một phương thức createAccount mới nhận địa chỉ email và mật khẩu,
xác thực các thông tin đó rồi tạo người dùng mới bằng phương thức
createUserWithEmailAndPassword.
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) } }
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); } } });
Thêm một biểu mẫu để đăng ký người dùng mới bằng email và mật khẩu của họ rồi gọi phương thức mới này khi biểu mẫu được gửi. Bạn có thể xem ví dụ trong mẫu bắt đầu nhanh của chúng tôi.
Đăng nhập người dùng hiện có
Tạo một phương thức signIn mới nhận địa chỉ email và mật khẩu,
xác thực các thông tin đó rồi đăng nhập người dùng bằng phương thức
signInWithEmailAndPassword.
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) } }
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); } } });
Thêm một biểu mẫu để đăng nhập người dùng bằng email và mật khẩu của họ rồi gọi phương thức mới này khi biểu mẫu được gửi. Bạn có thể xem ví dụ trong mẫu bắt đầu nhanh của chúng tôi.
Truy cập thông tin người dùng
Nếu người dùng đã đăng nhập thành công, bạn có thể lấy dữ liệu tài khoản của họ bất cứ lúc nào bằng phương thức getCurrentUser.
Kotlin
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(); }
Các bước tiếp theo
Khám phá các hướng dẫn về cách thêm các dịch vụ xác thực và danh tính khác: