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

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

หากต้องการความช่วยเหลือจาก AI ให้คัดลอกพรอมต์ด้านล่างลงใน เอเจนต์การเขียนโค้ด AI (เช่น Gemini ใน Android Studio, Antigravity, Claude Code, Codex และ Cursor) คุณสามารถปรับแต่งพรอมต์และทำซ้ำกับเอเจนต์ได้ ดูข้อมูลการติดตั้งโดยละเอียดได้ที่ ทักษะเอเจนต์ Firebase

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.

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

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

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

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

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

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

    (ทางเลือก)  เพิ่มการอ้างอิงไลบรารี 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: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. ระบุลายนิ้วมือ SHA-1 ของแอปหากยังไม่ได้ทำ

    1. ในFirebase Console ให้ไปที่ การตั้งค่า > แท็บทั่วไป

    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 นอกจากนี้ คุณยังต้องล้างสถานะข้อมูลเข้าสู่ระบบของผู้ใช้ปัจจุบันออกจากผู้ให้บริการข้อมูลเข้าสู่ระบบทั้งหมดตามที่เอกสารประกอบของเครื่องมือจัดการข้อมูลเข้าสู่ระบบแนะนำด้วย

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