Xác thực bằng Google trên Android

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ọ bằng cách tích hợp tính năng Đăng nhập bằng Google vào ứng dụng của bạn.

Để được trợ giúp AI, hãy sao chép câu lệnh bên dưới vào tác nhân lập trình AI (như Gemini trong Android Studio, Antigravity, Claude Code, Codex và Cursor). Bạn có thể tuỳ chỉnh câu lệnh và lặp lại với tác nhân. Truy cập vào trang Kỹ năng của tác nhân Firebase để biết thông tin chi tiết về cách cài đặt.

Help me use Firebase in my app.
1. Make sure that **Firebase agent skills** are installed and updated. For Claude Code, Codex, or Cursor agents, help me install the Firebase plugin. For other agents, run `npx skills add firebase/agent-skills`. Always try to use **Firebase agent skills** for Firebase-related tasks.
2. Help me set up and use Firebase Authentication with Google Sign-In in my app.

Trước khi bắt đầu

  1. Nếu bạn chưa thực hiện, hãy thêm Firebase vào dự án Android.

  2. Trong tệp Gradle (ở cấp ứng dụng) trong 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:35.2.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.

    (Cách khác)  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 phiên bản đó.

    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ả 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:25.0.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")
    }

  3. Chỉ định vân tay số SHA-1 của ứng dụng nếu bạn chưa làm.

    1. Trong bảng điều khiển Firebase, hãy chuyển đến thẻ Cài đặt > Chung.

    2. Di chuyển xuống thẻ Ứng dụng của bạn, chọn ứng dụng Android rồi thêm vân tay số SHA-1 vào trường Vân tay số chứng chỉ SHA.

    Hãy xem bài viết Xác thực ứng dụng của bạn để biết thông tin chi tiết về cách lấy vân tay số SHA của ứng dụng.

  4. Bật Google làm nhà cung cấp dịch vụ đăng nhập cho dự án Firebase của bạn:
    1. Trong bảng điều khiển Firebase, hãy chuyển đến phần Security (Bảo mật) > Authentication (Xác thực).
    2. Trong thẻ Sign-in method (Phương thức đăng nhập), hãy bật nhà cung cấp dịch vụ đăng nhập Google.
    3. Nhấp vào Lưu.
  5. Cập nhật tệp cấu hình Firebase.

    1. Khi được nhắc trong bảng điều khiển Firebase, 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 ứng dụng OAuth cần thiết để đăng nhập bằng Google.

    2. 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 hiện đã lỗi thời. (Xem phần Thêm Firebase vào dự án Android.)

Xác thực bằng Firebase

  1. 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 chung:
    1. 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ằng GetCredentialRequest:

      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 khách "máy chủ" đến phương thức setServerClientId. Cách tìm mã ứng dụng khách OAuth 2.0:

      1. Mở trang Thông tin xác thực trong bảng điều khiển Google Cloud.
      2. 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ợ.
    2. 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!");
          }
      }
  2. 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ượng FirebaseAuth:

    Kotlin

    private lateinit var auth: FirebaseAuth
    // ...
    // Initialize Firebase Auth
    auth = Firebase.auth

    Java

    private FirebaseAuth mAuth;
    // ...
    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
  3. 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:

    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);
    }
  4. Bây giờ, hãy lấy mã thông báo nhận dạng Google của người dùng được tạo ở bước 1, đổi mã đó 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:

    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);
                    }
                });
    }
    Nếu lệnh gọi đến signInWithCredential thành công, bạn có thể sử dụng phương thức getCurrentUser để 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 đăng nhập (tức là tên người dùng và mật khẩu, số điện thoại hoặc thông tin của nhà cung cấp dịch vụ xác thực) mà người dùng đã dùng để đăng nhập. Tài khoản mới này được lưu trữ trong 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 trong hồ sơ của người dùng từ đối tượng FirebaseUser. Xem phần Quản lý người dùng được quản lý.

  • 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 riêng biệt của người dùng đã đăng nhập từ biến auth, rồi dùng mã đó để 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 mình 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 hiện tại của người dùng khỏi tất cả trình cung cấp thông tin xác thực, theo đề xuất trong tài liệu về Trình quản lý thông tin xác thực:

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());
                }
            });
}