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

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

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

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

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

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

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

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

    Kotlin

    // 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

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

    Java

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

    Kotlin

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

    Kotlin

    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

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();