เริ่มต้นใช้งานการรับรองความถูกต้องของ Firebase บน Android

เชื่อมต่อแอปของคุณกับ Firebase

หากคุณยังไม่ได้ เพิ่ม Firebase ในโครงการ Android ของคุณ

เพิ่มการตรวจสอบสิทธิ์ Firebase ให้กับแอปของคุณ

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

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

    เมื่อใช้ Firebase Android BoM แอปของคุณจะใช้ไลบรารี Firebase Android เวอร์ชันที่เข้ากันได้เสมอ

    (ทางเลือก) เพิ่มการพึ่งพาไลบรารี Firebase โดยไม่ ใช้ BoM

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

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

  2. หากต้องการใช้ผู้ให้บริการตรวจสอบสิทธิ์ คุณต้องเปิดใช้งานใน คอนโซล Firebase ไปที่หน้าวิธีการลงชื่อเข้าใช้ในส่วนการตรวจสอบสิทธิ์ Firebase เพื่อเปิดใช้งานการลงชื่อเข้าใช้อีเมล/รหัสผ่านและผู้ให้บริการข้อมูลระบุตัวตนอื่นๆ ที่คุณต้องการสำหรับแอปของคุณ

(ไม่บังคับ) สร้างต้นแบบและทดสอบด้วย Firebase Local Emulator Suite

ก่อนที่จะพูดถึงวิธีที่แอปของคุณตรวจสอบสิทธิ์ผู้ใช้ เรามาแนะนำชุดเครื่องมือที่คุณสามารถใช้เพื่อสร้างต้นแบบและทดสอบฟังก์ชันการตรวจสอบสิทธิ์: Firebase Local Emulator Suite หากคุณกำลังตัดสินใจเลือกเทคนิคและผู้ให้บริการการตรวจสอบสิทธิ์ การลองใช้โมเดลข้อมูลที่แตกต่างกันด้วยข้อมูลสาธารณะและส่วนตัวโดยใช้กฎการตรวจสอบสิทธิ์และ Firebase Security Rules หรือการสร้างต้นแบบการออกแบบ UI การลงชื่อเข้าใช้ ความสามารถในการทำงานในพื้นที่โดยไม่ต้องปรับใช้บริการสดอาจเป็นความคิดที่ดี .

โปรแกรมจำลองการตรวจสอบสิทธิ์เป็นส่วนหนึ่งของ Local Emulator Suite ซึ่งช่วยให้แอปของคุณโต้ตอบกับเนื้อหาและการกำหนดค่าฐานข้อมูลที่จำลองได้ รวมถึงทรัพยากรโปรเจ็กต์ที่จำลอง (ฟังก์ชัน ฐานข้อมูลอื่น และกฎความปลอดภัย)

การใช้โปรแกรมจำลองการรับรองความถูกต้องมีเพียงไม่กี่ขั้นตอน:

  1. การเพิ่มบรรทัดโค้ดลงในการกำหนดค่าทดสอบของแอปเพื่อเชื่อมต่อกับโปรแกรมจำลอง
  2. จากรากของไดเร็กทอรีโปรเจ็กต์ในเครื่องของคุณ ให้รัน firebase emulators:start
  3. การใช้ Local Emulator Suite UI สำหรับการสร้างต้นแบบเชิงโต้ตอบ หรือ REST API โปรแกรมจำลองการตรวจสอบสิทธิ์สำหรับการทดสอบแบบไม่โต้ตอบ

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

ตอนนี้เรามาดูวิธีการตรวจสอบสิทธิ์ผู้ใช้กันต่อ

ตรวจสอบสถานะการรับรองความถูกต้องปัจจุบัน

  1. ประกาศอินสแตนซ์ของ FirebaseAuth

    Kotlin+KTX

    private lateinit var auth: FirebaseAuth

    Java

    private FirebaseAuth mAuth;
  2. ในเมธอด onCreate() ให้เริ่มต้นอินสแตนซ์ FirebaseAuth

    Kotlin+KTX

    // Initialize Firebase Auth
    auth = Firebase.auth

    Java

    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
  3. เมื่อเริ่มต้นกิจกรรมของคุณ ให้ตรวจสอบว่าผู้ใช้ลงชื่อเข้าใช้อยู่หรือไม่

    Kotlin+KTX

    public override fun onStart() {
        super.onStart()
        // Check if user is signed in (non-null) and update UI accordingly.
        val currentUser = auth.currentUser
        if (currentUser != null) {
            reload()
        }
    }

    Java

    @Override
    public void onStart() {
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        if(currentUser != null){
            reload();
        }
    }

ลงทะเบียนผู้ใช้ใหม่

สร้างเมธอด createAccount ใหม่ที่รับที่อยู่อีเมลและรหัสผ่าน ตรวจสอบความถูกต้อง และสร้างผู้ใช้ใหม่ด้วยเมธอด createUserWithEmailAndPassword

Kotlin+KTX

auth.createUserWithEmailAndPassword(email, password)
    .addOnCompleteListener(this) { task ->
        if (task.isSuccessful) {
            // Sign in success, update UI with the signed-in user's information
            Log.d(TAG, "createUserWithEmail:success")
            val user = auth.currentUser
            updateUI(user)
        } else {
            // If sign in fails, display a message to the user.
            Log.w(TAG, "createUserWithEmail:failure", task.exception)
            Toast.makeText(
                baseContext,
                "Authentication failed.",
                Toast.LENGTH_SHORT,
            ).show()
            updateUI(null)
        }
    }

Java

mAuth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d(TAG, "createUserWithEmail:success");
                    FirebaseUser user = mAuth.getCurrentUser();
                    updateUI(user);
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(TAG, "createUserWithEmail:failure", task.getException());
                    Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                    updateUI(null);
                }
            }
        });

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

ลงชื่อเข้าใช้ผู้ใช้ที่มีอยู่

สร้างวิธี signIn ใหม่ซึ่งรับที่อยู่อีเมลและรหัสผ่าน ตรวจสอบความถูกต้อง จากนั้นลงชื่อเข้าใช้ผู้ใช้ด้วยวิธี signInWithEmailAndPassword

Kotlin+KTX

auth.signInWithEmailAndPassword(email, password)
    .addOnCompleteListener(this) { task ->
        if (task.isSuccessful) {
            // Sign in success, update UI with the signed-in user's information
            Log.d(TAG, "signInWithEmail:success")
            val user = auth.currentUser
            updateUI(user)
        } else {
            // If sign in fails, display a message to the user.
            Log.w(TAG, "signInWithEmail:failure", task.exception)
            Toast.makeText(
                baseContext,
                "Authentication failed.",
                Toast.LENGTH_SHORT,
            ).show()
            updateUI(null)
        }
    }

Java

mAuth.signInWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d(TAG, "signInWithEmail:success");
                    FirebaseUser user = mAuth.getCurrentUser();
                    updateUI(user);
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(TAG, "signInWithEmail:failure", task.getException());
                    Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                    updateUI(null);
                }
            }
        });

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

เข้าถึงข้อมูลผู้ใช้

หากผู้ใช้ลงชื่อเข้าใช้สำเร็จ คุณจะรับข้อมูลบัญชีของผู้ใช้ได้ทุกเมื่อโดยใช้เมธอด getCurrentUser

Kotlin+KTX

val user = Firebase.auth.currentUser
user?.let {
    // Name, email address, and profile photo Url
    val name = it.displayName
    val email = it.email
    val photoUrl = it.photoUrl

    // Check if user's email is verified
    val emailVerified = it.isEmailVerified

    // The user's ID, unique to the Firebase project. Do NOT use this value to
    // authenticate with your backend server, if you have one. Use
    // FirebaseUser.getIdToken() instead.
    val uid = it.uid
}

Java

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    // Name, email address, and profile photo Url
    String name = user.getDisplayName();
    String email = user.getEmail();
    Uri photoUrl = user.getPhotoUrl();

    // Check if user's email is verified
    boolean emailVerified = user.isEmailVerified();

    // The user's ID, unique to the Firebase project. Do NOT use this value to
    // authenticate with your backend server, if you have one. Use
    // FirebaseUser.getIdToken() instead.
    String uid = user.getUid();
}

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

สำรวจคำแนะนำในการเพิ่มบริการระบุตัวตนและการตรวจสอบสิทธิ์อื่นๆ: