Bạn có thể cho phép người dùng xác thực bằng Firebase thông qua 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ủ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 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.
dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.10.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.
(Tuỳ chọn) 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 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, thì 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 { // 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.0.1")
// 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 dấu vân tay SHA của ứng dụng, hãy làm như vậy trên trang Cài đặt của bảng điều khiển Firebase. Hãy tham khảo bài viết Xác thực ứng dụng để biết thông tin chi tiết về cách lấy dấu 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 Firebase bảng điều khiển, hãy mở phần 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 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 (
google-services.json) xuống. Tệp này hiện chứa thông tin về ứ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 của bạn, thay thế tệp cấu hình tương ứng hiện đã lỗi thời. (Xem bài viết 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 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. Dưới đây là
hướng dẫn chung:
- Tạo thực thể cho yêu cầu đăng nhập bằng Google bằng
GetGoogleIdOption. Sau đó, tạo yêu cầu Trình quản lý thông tin xác thực bằngGetCredentialRequest:Kotlin
// 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()
Java
// 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ủ" đến phương thức
setServerClientId. Cách tìm mã ứng dụng 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 của loại Ứng dụng web là mã ứng dụng 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:
Kotlin
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!") } }
Java
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
- Trong phương thức
onCreatecủa hoạt động đăng nhập, hãy lấy thực thể dùng chung của đối tượngFirebaseAuthKotlin
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
Java
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 có đang đăng nhập hay không:
Kotlin
override fun onStart() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. val currentUser = auth.currentUser updateUI(currentUser) }
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); }
- 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:
Nếu lệnh gọi đến
Kotlin
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) } } }
Java
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); } }); }
signInWithCredentialthà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 tiên, 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 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ữ như một phần của dự án Firebase và có thể 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 bằng cách nào.
Trong ứng dụng, bạn có thể lấy thông tin cơ bản về hồ sơ của người dùng từ đối tượng
FirebaseUser. Xem bài viết Quản lý người dùng.Trong Firebase Realtime Database và Cloud Storage Quy tắc bảo mật, bạn có thể lấy mã nhận dạng người dùng duy nhất của người dùng đã đăng nhập từ biến
auth, và sử dụng mã này để 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 bằng nhiều 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 nhà cung cấp dịch vụ xác thực với 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 của người dùng hiện tại khỏi tất cả các 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:
Kotlin
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}") } } }
Java
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()); } }); }