Bạn có thể cho phép người dùng xác thực bằng Firebase bằng Tài khoản Google của họ.
Trước khi bắt đầu
Nếu bạn chưa thực hiện, hãy thêm Firebase vào dự án Android.
Trong tệp Gradle (ở cấp ứng dụng) của mô-đun (thường là
<project>/<app-module>/build.gradle.kts
hoặc<project>/<app-module>/build.gradle
), hãy thêm phần phụ thuộc cho thư viện Firebase Authentication dành cho Android. Bạn nên sử dụng Firebase Android BoM để kiểm soát việc tạo phiên bản thư viện.Ngoài ra, trong quá trình thiết lập Firebase Authentication, bạn cần thêm SDK Trình quản lý thông tin xác thực vào ứng dụng của mình.
dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:33.9.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")
// Also add the dependencies for the Credential Manager libraries and specify their versions implementation("androidx.credentials:credentials:1.3.0") implementation("androidx.credentials:credentials-play-services-auth:1.3.0") implementation("com.google.android.libraries.identity.googleid:googleid:1.1.1") }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.
Bạn đang tìm một mô-đun thư viện dành riêng cho Kotlin? Kể từ tháng 10 năm 2023 (Firebase BoM 32.5.0), cả nhà phát triển Kotlin và Java đều có thể phụ thuộc vào mô-đun thư viện chính (để biết thông tin chi tiết, hãy xem Câu hỏi thường gặp về sáng kiến này).(Phương án thay thế) Thêm phần phụ thuộc 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 của thư viện đó.
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:23.2.0")
// Also add the dependencies for the Credential Manager libraries and specify their versions implementation("androidx.credentials:credentials:1.3.0") implementation("androidx.credentials:credentials-play-services-auth:1.3.0") implementation("com.google.android.libraries.identity.googleid:googleid:1.1.1") }Nếu bạn chưa chỉ định vân tay SHA của ứng dụng, hãy thực hiện việc này trên trang Cài đặt của bảng điều khiển Firebase. Hãy tham khảo phần Xác thực ứng dụng để biết thông tin chi tiết về cách lấy vân tay SHA của ứng dụng.
- Bật Google làm phương thức đăng nhập trong bảng điều khiển Firebase:
- Trong bảng điều khiển Firebase, hãy mở phần Auth (Xác thực).
- Trên thẻ Phương thức đăng nhập, hãy bật phương thức đăng nhập bằng Google rồi nhấp vào Lưu.
Khi được nhắc trong bảng điều khiển, hãy tải tệp cấu hình Firebase đã cập nhật xuống (
google-services.json
). Tệp này hiện chứa thông tin ứng dụng OAuth cần thiết để đăng nhập bằng Google.Di chuyển tệp cấu hình đã cập nhật này vào dự án Android Studio, thay thế tệp cấu hình tương ứng đã lỗi thời. (Xem phần Thêm Firebase vào dự án Android.)
Xác thực bằng Firebase
- Tích hợp tính năng Đăng nhập bằng Google vào ứng dụng của bạn bằng cách làm theo các bước trong tài liệu về Trình quản lý thông tin xác thực. Sau đây là hướng dẫn tổng quan:
- Tạo thực thể cho yêu cầu đăng nhập bằng Google bằng cách sử dụng
GetGoogleIdOption
. Sau đó, hãy tạo yêu cầu Trình quản lý thông tin xác thực bằngGetCredentialRequest
:// Instantiate a Google sign-in request val googleIdOption = GetGoogleIdOption.Builder() // Your server's client ID, not your Android client ID. .setServerClientId(getString(R.string.default_web_client_id)) // Only show accounts previously used to sign in. .setFilterByAuthorizedAccounts(true) .build() // Create the Credential Manager request val request = GetCredentialRequest.Builder() .addCredentialOption(googleIdOption) .build()
// Instantiate a Google sign-in request GetGoogleIdOption googleIdOption = new GetGoogleIdOption.Builder() .setFilterByAuthorizedAccounts(true) .setServerClientId(getString(R.string.default_web_client_id)) .build(); // Create the Credential Manager request GetCredentialRequest request = new GetCredentialRequest.Builder() .addCredentialOption(googleIdOption) .build();
Trong yêu cầu ở trên, bạn phải truyền mã ứng dụng "máy chủ" của mình đến phương thức
setServerClientId
. Cách tìm mã ứng dụng khách OAuth 2.0:- Mở trang Thông tin xác thực trong bảng điều khiển Google Cloud.
- Mã ứng dụng khách loại Ứng dụng web là mã ứng dụng khách OAuth 2.0 của máy chủ phụ trợ.
- Kiểm tra để đảm bảo rằng sau khi bạn tích hợp tính năng Đăng nhập bằng Google, hoạt động đăng nhập của bạn có mã tương tự như sau:
private fun handleSignIn(credential: Credential) { // Check if credential is of type Google ID if (credential is CustomCredential && credential.type == TYPE_GOOGLE_ID_TOKEN_CREDENTIAL) { // Create Google ID Token val googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credential.data) // Sign in to Firebase with using the token firebaseAuthWithGoogle(googleIdTokenCredential.idToken) } else { Log.w(TAG, "Credential is not of type Google ID!") } }
private void handleSignIn(Credential credential) { // Check if credential is of type Google ID if (credential instanceof CustomCredential customCredential && credential.getType().equals(TYPE_GOOGLE_ID_TOKEN_CREDENTIAL)) { // Create Google ID Token Bundle credentialData = customCredential.getData(); GoogleIdTokenCredential googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credentialData); // Sign in to Firebase with using the token firebaseAuthWithGoogle(googleIdTokenCredential.getIdToken()); } else { Log.w(TAG, "Credential is not of type Google ID!"); } }
- Tạo thực thể cho yêu cầu đăng nhập bằng Google bằng cách sử dụng
- Trong phương thức
onCreate
của hoạt động đăng nhập, hãy lấy thực thể dùng chung của đối tượngFirebaseAuth
:private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
- Khi khởi chạy Hoạt động, hãy kiểm tra xem người dùng hiện đã đăng nhập hay chưa:
override fun onStart() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. val currentUser = auth.currentUser updateUI(currentUser) }
@Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); updateUI(currentUser); }
- Bây giờ, hãy lấy mã thông báo mã nhận dạng Google của người dùng được tạo ở bước 1, trao đổi mã thông báo đó để lấy thông tin xác thực Firebase và xác thực bằng Firebase bằng thông tin xác thực Firebase:
private fun firebaseAuthWithGoogle(idToken: String) { val credential = GoogleAuthProvider.getCredential(idToken, null) auth.signInWithCredential(credential) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success") val user = auth.currentUser updateUI(user) } else { // If sign in fails, display a message to the user Log.w(TAG, "signInWithCredential:failure", task.exception) updateUI(null) } } }
private void firebaseAuthWithGoogle(String idToken) { AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, task -> { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { // If sign in fails, display a message to the user Log.w(TAG, "signInWithCredential:failure", task.getException()); updateUI(null); } }); }
signInWithCredential
thành công, bạn có thể sử dụng phương thứcgetCurrentUser
để lấy dữ liệu tài khoản của người dùng.
Các bước tiếp theo
Sau khi người dùng đăng nhập lần đầu, một tài khoản người dùng mới sẽ được tạo và liên kết với thông tin xác thực (tức là tên người dùng và mật khẩu, số điện thoại hoặc thông tin về nhà cung cấp dịch vụ xác thực) mà người dùng đã đăng nhập. Tài khoản mới này được lưu trữ trong dự án Firebase và có thể được dùng để xác định người dùng trên mọi ứng dụng trong dự án, bất kể người dùng đăng nhập như thế nào.
Trong ứng dụng, bạn có thể lấy thông tin hồ sơ cơ bản của người dùng từ đối tượng
FirebaseUser
. Xem phần Quản lý người dùng.Trong Quy tắc bảo mật Firebase Realtime Database và Cloud Storage, bạn có thể lấy mã nhận dạng người dùng riêng biệt của người dùng đã đăng nhập từ biến
auth
và sử dụng mã nhận dạng đó để kiểm soát dữ liệu mà người dùng có thể truy cập.
Bạn có thể cho phép người dùng đăng nhập vào ứng dụng của bạn bằng nhiều trình cung cấp dịch vụ xác thực bằng cách liên kết thông tin xác thực của trình cung cấp dịch vụ xác thực với một tài khoản người dùng hiện có.
Để đăng xuất người dùng, hãy gọi
signOut
. Bạn cũng cần xoá trạng thái thông tin xác thực người dùng hiện tại khỏi tất cả trình cung cấp thông tin xác thực, như tài liệu về Trình quản lý thông tin xác thực đề xuất:
private fun signOut() { // Firebase sign out auth.signOut() // When a user signs out, clear the current user credential state from all credential providers. lifecycleScope.launch { try { val clearRequest = ClearCredentialStateRequest() credentialManager.clearCredentialState(clearRequest) updateUI(null) } catch (e: ClearCredentialException) { Log.e(TAG, "Couldn't clear user credentials: ${e.localizedMessage}") } } }
private void signOut() { // Firebase sign out mAuth.signOut(); // When a user signs out, clear the current user credential state from all credential providers. ClearCredentialStateRequest clearRequest = new ClearCredentialStateRequest(); credentialManager.clearCredentialStateAsync( clearRequest, new CancellationSignal(), Executors.newSingleThreadExecutor(), new CredentialManagerCallback<>() { @Override public void onResult(@NonNull Void result) { updateUI(null); } @Override public void onError(@NonNull ClearCredentialException e) { Log.e(TAG, "Couldn't clear user credentials: " + e.getLocalizedMessage()); } }); }