ตรวจสอบสิทธิ์โดยใช้การเข้าสู่ระบบ Facebook บน Android

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

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

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

  2. ในเว็บไซต์ Facebook for Developers ให้รับรหัสแอปและข้อมูลลับของแอปสำหรับแอปของคุณ
  3. เปิดใช้การเข้าสู่ระบบ Facebook โดยทำดังนี้
    1. ในคอนโซล Firebase ให้เปิดส่วนการตรวจสอบสิทธิ์
    2. ในแท็บวิธีการลงชื่อเข้าใช้ ให้เปิดใช้วิธีการลงชื่อเข้าใช้ Facebook และระบุ App ID และ App Secret ที่ได้รับจาก Facebook
    3. จากนั้นตรวจสอบว่า URI การเปลี่ยนเส้นทาง OAuth (เช่น my-app-12345.firebaseapp.com/__/auth/handler) อยู่ในรายการ URI การเปลี่ยนเส้นทาง OAuth ในหน้าการตั้งค่าของแอป Facebook ในเว็บไซต์ Facebook for Developers ในการกำหนดค่า การตั้งค่าผลิตภัณฑ์ > การเข้าสู่ระบบ Facebook
  4. ในไฟล์ Gradle ของโมดูล (ระดับแอป) (โดยทั่วไปจะเป็น <project>/<app-module>/build.gradle.kts หรือ <project>/<app-module>/build.gradle) ให้เพิ่มทรัพยากร Dependency สำหรับไลบรารีการตรวจสอบสิทธิ์ของ Firebase สำหรับ Android เราขอแนะนำให้ใช้ Firebase Android BoM เพื่อควบคุมการกำหนดเวอร์ชันไลบรารี

    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 จะ ขึ้นอยู่กับโมดูลไลบรารีหลัก (ดูรายละเอียดได้ที่ คําถามที่พบบ่อยเกี่ยวกับโครงการริเริ่มนี้)

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

  1. ผสานรวมการเข้าสู่ระบบด้วย Facebook ในแอปโดยทำตาม เอกสารประกอบของนักพัฒนาแอป เมื่อกำหนดค่าออบเจ็กต์ LoginButton หรือ LoginManager ให้ขอสิทธิ์ public_profile และ email หากคุณผสานรวมการเข้าสู่ระบบ Facebook โดยใช้ LoginButton กิจกรรมการลงชื่อเข้าใช้จะมีรหัสที่คล้ายกับตัวอย่างต่อไปนี้

    Kotlin+KTX

    // Initialize Facebook Login button
    callbackManager = CallbackManager.Factory.create()
    
    buttonFacebookLogin.setReadPermissions("email", "public_profile")
    buttonFacebookLogin.registerCallback(
        callbackManager,
        object : FacebookCallback<LoginResult> {
            override fun onSuccess(loginResult: LoginResult) {
                Log.d(TAG, "facebook:onSuccess:$loginResult")
                handleFacebookAccessToken(loginResult.accessToken)
            }
    
            override fun onCancel() {
                Log.d(TAG, "facebook:onCancel")
            }
    
            override fun onError(error: FacebookException) {
                Log.d(TAG, "facebook:onError", error)
            }
        },
    )
    // ...
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
    
        // Pass the activity result back to the Facebook SDK
        callbackManager.onActivityResult(requestCode, resultCode, data)
    }

    Java

    // Initialize Facebook Login button
    mCallbackManager = CallbackManager.Factory.create();
    LoginButton loginButton = findViewById(R.id.button_sign_in);
    loginButton.setReadPermissions("email", "public_profile");
    loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Log.d(TAG, "facebook:onSuccess:" + loginResult);
            handleFacebookAccessToken(loginResult.getAccessToken());
        }
    
        @Override
        public void onCancel() {
            Log.d(TAG, "facebook:onCancel");
        }
    
        @Override
        public void onError(FacebookException error) {
            Log.d(TAG, "facebook:onError", error);
        }
    });
    // ...
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        // Pass the activity result back to the Facebook SDK
        mCallbackManager.onActivityResult(requestCode, resultCode, data);
    }
  2. ในเมธอด onCreate ของกิจกรรมการลงชื่อเข้าใช้ ให้รับอินสแตนซ์ที่แชร์ของออบเจ็กต์ FirebaseAuth ดังนี้

    Kotlin+KTX

    private lateinit var auth: FirebaseAuth
    // ...
    // Initialize Firebase Auth
    auth = Firebase.auth

    Java

    private FirebaseAuth mAuth;
    // ...
    // 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
        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. หลังจากที่ผู้ใช้ลงชื่อเข้าใช้สำเร็จแล้ว ในเมธอด Callback onSuccess ของ LoginButton ให้รับโทเค็นเพื่อการเข้าถึงสำหรับผู้ใช้ที่ลงชื่อเข้าใช้ แลกเปลี่ยนกับเป็นข้อมูลเข้าสู่ระบบ Firebase และตรวจสอบสิทธิ์กับ Firebase โดยใช้ข้อมูลเข้าสู่ระบบ Firebase:

    Kotlin+KTX

    private fun handleFacebookAccessToken(token: AccessToken) {
        Log.d(TAG, "handleFacebookAccessToken:$token")
    
        val credential = FacebookAuthProvider.getCredential(token.token)
        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)
                    Toast.makeText(
                        baseContext,
                        "Authentication failed.",
                        Toast.LENGTH_SHORT,
                    ).show()
                    updateUI(null)
                }
            }
    }

    Java

    private void handleFacebookAccessToken(AccessToken token) {
        Log.d(TAG, "handleFacebookAccessToken:" + token);
    
        AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
        mAuth.signInWithCredential(credential)
                .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, "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());
                            Toast.makeText(FacebookLoginActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                            updateUI(null);
                        }
                    }
                });
    }
    หากโทรหา signInWithCredential สําเร็จ คุณจะใช้เมธอด getCurrentUser เพื่อรับข้อมูลบัญชีของผู้ใช้ได้

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

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

  • คุณดูข้อมูลโปรไฟล์พื้นฐานของผู้ใช้จากออบเจ็กต์ FirebaseUser ในแอปได้ โปรดดูที่ จัดการผู้ใช้

  • ในกฎความปลอดภัยของ Firebase Realtime Database และ Cloud Storage คุณจะรับรหัสผู้ใช้ที่ไม่ซ้ำของผู้ใช้ที่ลงชื่อเข้าใช้จากตัวแปร auth ได้ และใช้รหัสดังกล่าวเพื่อควบคุมข้อมูลที่ผู้ใช้เข้าถึงได้

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

หากต้องการนำผู้ใช้ออกจากระบบ โปรดโทรหา signOut:

Kotlin+KTX

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();