Catch up on highlights from Firebase at Google I/O 2023. Learn more

เริ่มต้นใช้งาน Firebase Authentication บน Android

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

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

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

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

Kotlin+KTX

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

เมื่อใช้ 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-ktx:22.0.0'
}

Java

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

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

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

ก่อนที่จะพูดถึงวิธีที่แอปตรวจสอบสิทธิ์ผู้ใช้ ขอแนะนำชุดเครื่องมือที่คุณสามารถใช้เพื่อสร้างต้นแบบและทดสอบฟังก์ชันการตรวจสอบสิทธิ์: Firebase Local Emulator Suite หากคุณกำลังตัดสินใจเลือกเทคนิคการตรวจสอบสิทธิ์และผู้ให้บริการ การลองใช้โมเดลข้อมูลต่างๆ กับข้อมูลสาธารณะและข้อมูลส่วนตัวโดยใช้กฎความปลอดภัยการตรวจสอบสิทธิ์และ Firebase หรือการออกแบบ 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();
}

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

สำรวจคำแนะนำเกี่ยวกับการเพิ่มบริการระบุตัวตนและการรับรองความถูกต้องอื่นๆ: