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 thông qua Tài khoản Google của họ.

Trước khi bắt đầu

  1. Nếu 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) 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 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 Credential Manager SDK vào ứng dụng của mình.

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:34.0.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 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 phiên bản đó.

    Xin lưu ý rằng nếu 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.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. Nếu bạn chưa chỉ định vân tay số 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 phần 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.

  4. Bật Google làm phương thức đăng nhập trong bảng điều khiển Firebase:
    1. Trong bảng điều khiển Firebase, hãy mở mục Auth (Uỷ quyền).
    2. 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.
  5. 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 cho tính năng đăng nhập bằng Google.

  6. 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 tổng quát:
    1. Tạo thực thể cho yêu cầu đăng nhập bằng Google bằ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 cách sử dụ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ã nhận dạng ứ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:

      1. Mở trang Thông tin đăng nhập trong bảng điều khiển Google Cloud.
      2. Mã ứng dụng khách thuộc 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 sẽ 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 phiên bản 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 có đă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);
    }
  4. Bây giờ, hãy lấy mã thông báo nhận dạng của người dùng do Google tạo ở bước 1, trao đổi mã thông báo đó để lấy thông tin đăng nhập Firebase và xác thực bằng Firebase bằng thông tin đăng nhập 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ể 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 nhà cung cấp dịch vụ uỷ quyền) mà người dùng đã đăng nhập. Tài khoản mới này được lưu trữ trong dự án Firebase của bạn và có thể dùng để xác định một 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 các ứng dụng của mình, 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 phần Quản lý người dùng.

  • Trong Firebase Realtime DatabaseCloud 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 và dùng mã nhận dạng 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 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 đăng nhập 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 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 khuyến nghị của tài liệu 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());
                }
            });
}