通过将 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:31.2.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:21.1.0' }
Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.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:21.1.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();