เริ่มต้นใช้งานการตรวจสอบสิทธิ์ Firebase ใน Android

เชื่อมต่อแอปกับ Firebase

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

เพิ่มการตรวจสอบสิทธิ์ Firebase ลงในแอป

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

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:33.1.2"))
    
        // 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 เวอร์ชันที่เข้ากันได้เสมอ

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

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

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

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

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

การใช้โปรแกรมจำลองการตรวจสอบสิทธิ์มีเพียงไม่กี่ขั้นตอนดังนี้

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

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

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

ตรวจสอบสถานะการตรวจสอบสิทธิ์ปัจจุบัน

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

    Kotlin+KTX

    private lateinit var auth: FirebaseAuth

    Java

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

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

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

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