Bạn có thể sử dụng Xác thực Firebase để tạo và sử dụng các tài khoản ẩn danh tạm thời để xác thực với Firebase. Các tài khoản ẩn danh tạm thời này có thể được sử dụng để cho phép người dùng chưa đăng ký ứng dụng của bạn làm việc với dữ liệu được bảo vệ bởi các quy tắc bảo mật. Nếu người dùng ẩn danh quyết định đăng ký ứng dụng của bạn, bạn có thể liên kết thông tin xác thực đăng nhập của họ với tài khoản ẩn danh để họ có thể tiếp tục làm việc với dữ liệu được bảo vệ của họ trong các phiên sau này.
Trước khi bắt đầu
- Nếu bạn chưa có, hãy thêm Firebase vào dự án Android của bạn .
- Sử dụng Firebase Android BoM , khai báo phần phụ thuộc cho thư viện Android Xác thực Firebase trong tệp Gradle mô-đun (cấp ứng dụng) của bạn (thường là
app/build.gradle
).Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:30.1.0') // Declare 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 các phiên bản tương thích của thư viện Firebase Android.
(Thay thế) Khai báo các phụ thuộc thư viện Firebase mà không cần sử dụng BoM
Nếu bạn 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ụ thuộc của nó.
Lưu ý rằng nếu bạn sử dụng nhiều thư viện Firebase trong ứng dụng của mình, chúng tôi thực sự khuyên bạn nên sử dụng BoM để quản lý các phiên bản thư viện, điều này đảm bảo rằng tất cả các phiên bản đều tương thích.
dependencies { // Declare 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:21.0.5' }
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:30.1.0') // Declare 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-ktx' }
Bằng cách sử dụng Firebase Android BoM , ứng dụng của bạn sẽ luôn sử dụng các phiên bản tương thích của thư viện Firebase Android.
(Thay thế) Khai báo các phụ thuộc thư viện Firebase mà không cần sử dụng BoM
Nếu bạn 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ụ thuộc của nó.
Lưu ý rằng nếu bạn sử dụng nhiều thư viện Firebase trong ứng dụng của mình, chúng tôi thực sự khuyên bạn nên sử dụng BoM để quản lý các phiên bản thư viện, điều này đảm bảo rằng tất cả các phiên bản đều tương thích.
dependencies { // Declare 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-ktx:21.0.5' }
- Nếu bạn chưa kết nối ứng dụng của mình với dự án Firebase, hãy làm như vậy từ bảng điều khiển Firebase .
- Bật xác thực ẩn danh:
- Trong bảng điều khiển Firebase , hãy mở phần Xác thực.
- Trên trang Phương thức đăng nhập, hãy bật phương thức đăng nhập Ẩn danh .
Xác thực ẩn danh với Firebase
Khi người dùng đã đăng xuất sử dụng tính năng ứng dụng yêu cầu xác thực với Firebase, hãy đăng nhập ẩn danh người dùng đó bằng cách hoàn thành các bước sau:
- Trong phương thức
onCreate
của hoạt động của bạn, hãy lấy phiên bản được chia sẻ của đối tượngFirebaseAuth
:Java
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
Kotlin+KTX
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
- Khi khởi chạy Hoạt động của bạn, hãy kiểm tra xem người dùng hiện đã đăng nhập hay chưa:
Java
@Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); updateUI(currentUser); }
Kotlin+KTX
public override fun onStart() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. val currentUser = auth.currentUser updateUI(currentUser) }
- Cuối cùng, hãy gọi
signInAnonymously
nặc danh để đăng nhập với tư cách người dùng ẩn danh:Nếu đăng nhập thành công, bạn có thể sử dụng phương thứcJava
mAuth.signInAnonymously() .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, "signInAnonymously:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInAnonymously:failure", task.getException()); Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); updateUI(null); } } });
Kotlin+KTX
auth.signInAnonymously() .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInAnonymously:success") val user = auth.currentUser updateUI(user) } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInAnonymously:failure", task.exception) Toast.makeText(baseContext, "Authentication failed.", Toast.LENGTH_SHORT).show() updateUI(null) } }
getCurrentUser
để lấy dữ liệu tài khoản của người dùng.
Chuyển đổi tài khoản ẩn danh thành tài khoản vĩnh viễn
Khi một người dùng ẩn danh đăng ký ứng dụng của bạn, bạn có thể muốn cho phép họ tiếp tục công việc với tài khoản mới của họ — ví dụ: bạn có thể muốn cung cấp các mặt hàng mà người dùng đã thêm vào giỏ hàng của họ trước khi họ đăng ký giỏ hàng của tài khoản. Để làm như vậy, hãy hoàn thành các bước sau:
- Khi người dùng đăng ký, hãy hoàn tất quy trình đăng nhập cho nhà cung cấp xác thực của người dùng, nhưng không bao gồm, gọi một trong các phương thức
FirebaseAuth.signInWith
. Ví dụ: lấy mã thông báo ID Google, mã thông báo truy cập Facebook hoặc địa chỉ email và mật khẩu của người dùng. Nhận thông tin
AuthCredential
thực cho nhà cung cấp xác thực mới:Đăng nhập Google
Java
AuthCredential credential = GoogleAuthProvider.getCredential(googleIdToken, null);
Kotlin+KTX
val credential = GoogleAuthProvider.getCredential(googleIdToken, null)
Đăng nhập Facebook
Java
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
Kotlin+KTX
val credential = FacebookAuthProvider.getCredential(token.token)
Đăng nhập bằng mật khẩu email
Java
AuthCredential credential = EmailAuthProvider.getCredential(email, password);
Kotlin+KTX
val credential = EmailAuthProvider.getCredential(email, password)
Chuyển đối tượng
AuthCredential
đến phương thứclinkWithCredential
của người dùng đăng nhập:Java
mAuth.getCurrentUser().linkWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Log.d(TAG, "linkWithCredential:success"); FirebaseUser user = task.getResult().getUser(); updateUI(user); } else { Log.w(TAG, "linkWithCredential:failure", task.getException()); Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); updateUI(null); } } });
Kotlin+KTX
auth.currentUser!!.linkWithCredential(credential) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { Log.d(TAG, "linkWithCredential:success") val user = task.result?.user updateUI(user) } else { Log.w(TAG, "linkWithCredential:failure", task.exception) Toast.makeText(baseContext, "Authentication failed.", Toast.LENGTH_SHORT).show() updateUI(null) } }
Nếu lệnh gọi đến
linkWithCredential
thành công, tài khoản mới của người dùng có thể truy cập vào dữ liệu Firebase của tài khoản ẩn danh.Bước tiếp theo
Giờ đây, người dùng có thể xác thực bằng Firebase, bạn có thể kiểm soát quyền truy cập của họ vào dữ liệu trong cơ sở dữ liệu Firebase của bạn bằng cách sử dụng các quy tắc Firebase .
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2022-05-26 UTC.
[{ "type": "thumb-down", "id": "missingTheInformationINeed", "label":"Missing the information I need" },{ "type": "thumb-down", "id": "tooComplicatedTooManySteps", "label":"Too complicated / too many steps" },{ "type": "thumb-down", "id": "outOfDate", "label":"Out of date" },{ "type": "thumb-down", "id": "translationIssue", "label":"Translation issue" },{ "type": "thumb-down", "id": "samplesCodeIssue", "label":"Vấn đề về mẫu/mã" },{ "type": "thumb-down", "id": "otherDown", "label":"Other" }] [{ "type": "thumb-up", "id": "easyToUnderstand", "label":"Easy to understand" },{ "type": "thumb-up", "id": "solvedMyProblem", "label":"Solved my problem" },{ "type": "thumb-up", "id": "otherUp", "label":"Other" }]