ตรวจสอบสิทธิ์กับ Google ใน Android

คุณสามารถอนุญาตให้ผู้ใช้ตรวจสอบสิทธิ์กับ Firebase โดยใช้บัญชี Google ได้

ก่อนเริ่มต้น

  1. เพิ่ม Firebase ลงในโปรเจ็กต์ Android หากยังไม่ได้เพิ่ม

  2. ในไฟล์ Gradle ระดับโมดูลหรือระดับแอป (โดยมากจะเป็น <project>/<app-module>/build.gradle.kts หรือ <project>/<app-module>/build.gradle) ให้เพิ่มทรัพยากร Dependency สำหรับไลบรารี Firebase Authentication สำหรับ Android เราขอแนะนำให้ใช้ Firebase Android BoM เพื่อควบคุมการกำหนดเวอร์ชันของไลบรารี

    นอกจากนี้ คุณยังต้องเพิ่ม Credential Manager SDK ลงในแอปด้วย ซึ่งเป็นส่วนหนึ่งของการตั้งค่าFirebase Authentication

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:34.18.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")
    }

    การใช้ Firebase Android BoM, จะทำให้แอปใช้ไลบรารี Firebase Android เวอร์ชันที่เข้ากันได้อยู่เสมอ

    (อีกวิธีหนึ่ง)  เพิ่มทรัพยากร Dependency ของไลบรารี Firebase โดยไม่ ใช้ BoM

    หากเลือกที่จะไม่ใช้ Firebase BoM คุณต้องระบุเวอร์ชันของไลบรารี Firebase แต่ละรายการ ในบรรทัดทรัพยากร Dependency

    โปรดทราบว่าหากคุณใช้ไลบรารี Firebase หลายรายการ ในแอป เราขอแนะนำอย่างยิ่งให้ใช้ BoM เพื่อจัดการเวอร์ชันของไลบรารี ซึ่งจะช่วยให้มั่นใจได้ว่าทุกเวอร์ชันเข้ากันได้

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

  3. ระบุลายนิ้วมือ SHA-1 ของแอปหากยังไม่ได้ระบุ

    1. ในคอนโซล Firebase ให้ไปที่ Settings > แท็บทั่วไป

    2. เลื่อนลงไปที่การ์ดแอปของคุณ เลือกแอป Android แล้วเพิ่มลายนิ้วมือ SHA-1 ในช่องลายนิ้วมือของใบรับรอง SHA

    ดูรายละเอียดเกี่ยวกับวิธีรับลายนิ้วมือ SHA ของแอปได้ที่หัวข้อการตรวจสอบสิทธิ์ไคลเอ็นต์

  4. เปิดใช้ Google เป็นผู้ให้บริการลงชื่อเข้าใช้สำหรับโปรเจ็กต์ Firebase โดยทำดังนี้
    1. ในคอนโซล Firebase ให้ไปที่ ความปลอดภัย > การตรวจสอบสิทธิ์
    2. ในแท็บวิธีการลงชื่อเข้าใช้ ให้เปิดใช้ผู้ให้บริการลงชื่อเข้าใช้ Google
    3. คลิกบันทึก
  5. อัปเดตไฟล์กำหนดค่า Firebase

    1. เมื่อระบบแจ้งในคอนโซล Firebase ให้ดาวน์โหลดไฟล์กำหนดค่า Firebase ที่อัปเดตแล้ว (google-services.json) ซึ่งตอนนี้มีข้อมูลไคลเอ็นต์ OAuth ที่จำเป็นสำหรับการลงชื่อเข้าใช้ด้วยบัญชี Google

    2. ย้ายไฟล์กำหนดค่าที่อัปเดตนี้ไปยังโปรเจ็กต์ Android Studio โดยให้ แทนที่ ไฟล์กำหนดค่าที่เกี่ยวข้องซึ่งล้าสมัยแล้ว (ดูหัวข้อ เพิ่ม Firebase ลงในโปรเจ็กต์ Android)

ตรวจสอบสิทธิ์ด้วย Firebase

  1. ผสานรวมการลงชื่อเข้าใช้ด้วย Google ลงในแอปโดยทำตามขั้นตอนใน เอกสารประกอบของ Credential Manager วิธีการโดยคร่าวๆ มีดังนี้
    1. สร้างอินสแตนซ์คำขอลงชื่อเข้าใช้ด้วยบัญชี Google โดยใช้ GetGoogleIdOption. จากนั้นสร้างคำขอ Credential Manager โดยใช้ 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();

      ในคำขอข้างต้น คุณต้องส่งรหัสไคลเอ็นต์ "เซิร์ฟเวอร์" ไปยัง setServerClientId เมธอด วิธีค้นหา รหัสไคลเอ็นต์ OAuth 2.0

      1. เปิดหน้า ข้อมูลเข้าสู่ระบบ ในคอนโซล Google Cloud
      2. รหัสไคลเอ็นต์ประเภทเว็บแอปพลิเคชัน คือรหัสไคลเอ็นต์ OAuth 2.0 ของเซิร์ฟเวอร์แบ็กเอนด์
    2. ตรวจสอบว่าหลังจากผสานรวมการลงชื่อเข้าใช้ด้วย Google แล้ว กิจกรรมการลงชื่อเข้าใช้มีโค้ดที่คล้ายกับโค้ดต่อไปนี้

      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. ในเมธอด onCreate ของกิจกรรมการลงชื่อเข้าใช้ ให้รับอินสแตนซ์ที่แชร์ ของออบเจ็กต์ FirebaseAuth ดังนี้

    Kotlin

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

    Java

    private FirebaseAuth mAuth;
    // ...
    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
  3. เมื่อเริ่มต้นใช้งานกิจกรรม ให้ตรวจสอบว่าผู้ใช้ลงชื่อเข้าใช้อยู่หรือไม่ โดยทำดังนี้

    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. ตอนนี้ให้รับโทเค็นรหัส Google ของผู้ใช้ที่สร้างขึ้นในขั้นตอนที่ 1 แลกโทเค็นดังกล่าวเป็นข้อมูลเข้าสู่ระบบ Firebase แล้วตรวจสอบสิทธิ์กับ Firebase โดยใช้ข้อมูลเข้าสู่ระบบ 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);
                    }
                });
    }
    หากการเรียก signInWithCredential สำเร็จ คุณจะใช้เมธอด getCurrentUser เพื่อรับข้อมูลบัญชีของผู้ใช้ได้

ขั้นตอนถัดไป

หลังจากที่ผู้ใช้ลงชื่อเข้าใช้เป็นครั้งแรก ระบบจะสร้างบัญชีผู้ใช้ใหม่และลิงก์กับข้อมูลเข้าสู่ระบบ เช่น ชื่อผู้ใช้และรหัสผ่าน หมายเลขโทรศัพท์ หรือข้อมูลผู้ให้บริการตรวจสอบสิทธิ์ที่ผู้ใช้ใช้ลงชื่อเข้าใช้ ระบบจะจัดเก็บบัญชีใหม่นี้ไว้เป็นส่วนหนึ่งของโปรเจ็กต์ Firebase และใช้เพื่อระบุผู้ใช้ในทุกแอปของโปรเจ็กต์ได้ ไม่ว่าผู้ใช้จะลงชื่อเข้าใช้ด้วยวิธีใดก็ตาม

  • ในแอป คุณสามารถรับข้อมูลโปรไฟล์พื้นฐานของผู้ใช้จาก FirebaseUser ออบเจ็กต์ได้ ดูหัวข้อ จัดการผู้ใช้

  • ใน Firebase Realtime Database และ Cloud Storage กฎความปลอดภัย คุณสามารถ รับรหัสผู้ใช้ที่ไม่ซ้ำกันของผู้ใช้ที่ลงชื่อเข้าใช้จากตัวแปร auth และใช้รหัสนี้เพื่อควบคุมข้อมูลที่ผู้ใช้เข้าถึงได้

คุณสามารถอนุญาตให้ผู้ใช้ลงชื่อเข้าใช้แอปโดยใช้ผู้ให้บริการตรวจสอบสิทธิ์หลายรายได้ด้วยการลิงก์ข้อมูลเข้าสู่ระบบของผู้ให้บริการตรวจสอบสิทธิ์กับบัญชีผู้ใช้ที่มีอยู่

หากต้องการออกจากระบบผู้ใช้ ให้เรียกใช้ signOut นอกจากนี้ คุณยังต้องล้างสถานะข้อมูลเข้าสู่ระบบของผู้ใช้ปัจจุบัน จากผู้ให้บริการข้อมูลเข้าสู่ระบบทั้งหมดตามที่เอกสารประกอบของ Credential Managerแนะนำไว้ด้วย โดยทำดังนี้

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