通過將 Facebook 登錄集成到您的應用程序,您可以讓您的用戶使用他們的 Facebook 帳戶通過 Firebase 進行身份驗證。
在你開始之前
如果您還沒有,請將 Firebase 添加到您的 Android 項目中。
- 在Facebook for Developers網站上,為您的應用獲取App ID和App Secret 。
- 啟用 Facebook 登錄:
- 在Firebase 控制台中,打開Auth部分。
- 在Sign in method選項卡上,啟用Facebook登錄方法並指定您從 Facebook 獲得的App ID和App Secret 。
- 然後,確保您的OAuth 重定向 URI (例如
my-app-12345.firebaseapp.com/__/auth/handler
)在產品的Facebook for Developers站點上的 Facebook 應用程序設置頁面中被列為您的OAuth 重定向 URI之一設置 > Facebook 登錄配置。
在您的模塊(應用級)Gradle 文件(通常為
<project>/<app-module>/build.gradle
)中,添加 Firebase 身份驗證 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 庫。
(備選)在不使用 BoM 的情況下添加 Firebase 庫依賴項
如果您選擇不使用 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 庫。
(備選)在不使用 BoM 的情況下添加 Firebase 庫依賴項
如果您選擇不使用 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 進行身份驗證
- 按照開發人員的文檔將 Facebook 登錄集成到您的應用程序中。當您配置
LoginButton
或LoginManager
對象時,請求public_profile
和email
權限。如果您使用LoginButton
集成 Facebook 登錄,則您的登錄活動的代碼類似於以下內容: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); }
- 在登錄活動的
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();
- 初始化 Activity 時,檢查用戶當前是否已登錄:
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); }
- 用戶成功登錄後,在
LoginButton
的onSuccess
回調方法中,獲取登錄用戶的訪問令牌,將其交換為 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 Security Rules中,您可以從
auth
變量中獲取登錄用戶的唯一用戶 ID,並使用它來控制用戶可以訪問哪些數據。
您可以允許用戶使用多個身份驗證提供程序登錄您的應用程序,方法是將身份驗證提供程序憑據鏈接到現有用戶帳戶。
要註銷用戶,請調用signOut
:
Kotlin+KTX
Firebase.auth.signOut()
Java
FirebaseAuth.getInstance().signOut();