ตรวจสอบสิทธิ์กับ 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 เพื่อควบคุมการกำหนดเวอร์ชันของไลบรารี

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

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

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

    หากเลือกไม่ใช้ 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:23.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")
    }
    หากกำลังมองหาโมดูลไลบรารีสำหรับ Kotlin โดยเฉพาะ ตั้งแต่เดือนตุลาคม 2023 (Firebase BoM 32.5.0) เป็นต้นไป นักพัฒนาซอฟต์แวร์ทั้ง Kotlin และ Java จะใช้โมดูลไลบรารีหลักได้ (ดูรายละเอียดได้ในคําถามที่พบบ่อยเกี่ยวกับโครงการริเริ่มนี้)

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

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

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

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

  1. ผสานรวมฟีเจอร์ลงชื่อเข้าใช้ด้วย Google เข้ากับแอปโดยทําตามขั้นตอนในเอกสารประกอบเกี่ยวกับเครื่องมือจัดการข้อมูลเข้าสู่ระบบ วิธีการระดับสูงมีดังนี้
    1. สร้างอินสแตนซ์คำขอลงชื่อเข้าใช้ Google โดยใช้ GetGoogleIdOption จากนั้นสร้างคำขอเครื่องมือจัดการข้อมูลเข้าสู่ระบบโดยใช้ GetCredentialRequest โดยทำดังนี้
      KotlinJava
      // 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()
      // 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 แล้ว กิจกรรมการลงชื่อเข้าใช้ของคุณจะมีโค้ดคล้ายกับตัวอย่างต่อไปนี้
      KotlinJava
      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!")
          }
      }
      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 ดังนี้
    KotlinJava
    private lateinit var auth: FirebaseAuth
    // ...
    // Initialize Firebase Auth
    auth = Firebase.auth
    private FirebaseAuth mAuth;
    // ...
    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
  3. เมื่อเริ่มต้นกิจกรรม ให้ตรวจสอบว่าผู้ใช้ลงชื่อเข้าใช้อยู่หรือไม่ โดยทำดังนี้
    KotlinJava
    override fun onStart() {
        super.onStart()
        // Check if user is signed in (non-null) and update UI accordingly.
        val currentUser = auth.currentUser
        updateUI(currentUser)
    }
    @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 โดยทำดังนี้
    KotlinJava
    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)
                }
            }
    }
    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 แนะนำ ดังนี้

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