您可以让您的用户使用他们的 Google 帐户通过 Firebase 进行身份验证。
在你开始之前
如果您还没有,请将 Firebase 添加到您的 Android 项目中。
在您的模块(应用级)Gradle 文件(通常为
<project>/<app-module>/build.gradle
)中,添加 Firebase 身份验证 Android 库的依赖项。我们建议使用Firebase Android BoM来控制库版本。此外,作为设置 Firebase 身份验证的一部分,您需要将 Google Play 服务 SDK 添加到您的应用程序中。
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'
// Also add the dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:20.4.1' }通过使用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'
// Also add the dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:20.4.1' }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'
// Also add the dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:20.4.1' }通过使用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'
// Also add the dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:20.4.1' }如果您尚未指定应用的 SHA-1 指纹,请从 Firebase 控制台的“设置”页面执行此操作。有关如何获取应用的 SHA-1 指纹的详细信息,请参阅验证您的客户端。
- 在 Firebase 控制台中启用 Google 作为登录方法:
- 在Firebase 控制台中,打开Auth部分。
- 在登录方法选项卡上,启用Google登录方法并单击保存。
使用 Firebase 进行身份验证
- 按照使用保存的凭据登录用户页面上的步骤,将 Google One Tap 登录集成到您的应用程序中。配置
BeginSignInRequest
对象时,调用setGoogleIdTokenRequestOptions
:您必须将“服务器”客户端 ID 传递给Kotlin+KTX
signInRequest = BeginSignInRequest.builder() .setGoogleIdTokenRequestOptions( BeginSignInRequest.GoogleIdTokenRequestOptions.builder() .setSupported(true) // Your server's client ID, not your Android client ID. .setServerClientId(getString(R.string.your_web_client_id)) // Only show accounts previously used to sign in. .setFilterByAuthorizedAccounts(true) .build()) .build()
Java
signInRequest = BeginSignInRequest.builder() .setGoogleIdTokenRequestOptions(GoogleIdTokenRequestOptions.builder() .setSupported(true) // Your server's client ID, not your Android client ID. .setServerClientId(getString(R.string.default_web_client_id)) // Only show accounts previously used to sign in. .setFilterByAuthorizedAccounts(true) .build()) .build();
setGoogleIdTokenRequestOptions
方法。要查找 OAuth 2.0 客户端 ID:- 在 GCP Console 中打开凭据页面。
- Web 应用程序类型客户端 ID 是后端服务器的 OAuth 2.0 客户端 ID。
Kotlin+KTX
class YourActivity : AppCompatActivity() { // ... private val REQ_ONE_TAP = 2 // Can be any integer unique to the Activity private var showOneTapUI = true // ... override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { REQ_ONE_TAP -> { try { val credential = oneTapClient.getSignInCredentialFromIntent(data) val idToken = credential.googleIdToken when { idToken != null -> { // Got an ID token from Google. Use it to authenticate // with Firebase. Log.d(TAG, "Got ID token.") } else -> { // Shouldn't happen. Log.d(TAG, "No ID token!") } } } catch (e: ApiException) { // ... } } } // ... }
Java
public class YourActivity extends AppCompatActivity { // ... private static final int REQ_ONE_TAP = 2; // Can be any integer unique to the Activity. private boolean showOneTapUI = true; // ... @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQ_ONE_TAP: try { SignInCredential credential = oneTapClient.getSignInCredentialFromIntent(data); String idToken = credential.getGoogleIdToken(); if (idToken != null) { // Got an ID token from Google. Use it to authenticate // with Firebase. Log.d(TAG, "Got ID token."); } } catch (ApiException e) { // ... } break; } } }
- 在登录活动的
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
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); }
- 在您的
onActivityResult()
处理程序中(参见第 1 步),获取用户的 Google ID 令牌,将其交换为 Firebase 凭证,并使用 Firebase 凭证通过 Firebase 进行身份验证:如果对Kotlin+KTX
val googleCredential = oneTapClient.getSignInCredentialFromIntent(data) val idToken = googleCredential.googleIdToken when { idToken != null -> { // Got an ID token from Google. Use it to authenticate // with Firebase. val firebaseCredential = GoogleAuthProvider.getCredential(idToken, null) auth.signInWithCredential(firebaseCredential) .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) updateUI(null) } } } else -> { // Shouldn't happen. Log.d(TAG, "No ID token!") } }
Java
SignInCredential googleCredential = oneTapClient.getSignInCredentialFromIntent(data); String idToken = googleCredential.getGoogleIdToken(); if (idToken != null) { // Got an ID token from Google. Use it to authenticate // with Firebase. AuthCredential firebaseCredential = GoogleAuthProvider.getCredential(idToken, null); mAuth.signInWithCredential(firebaseCredential) .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()); 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();