您可以讓用戶使用其 Google 帳號通過 Firebase 進行身份驗證。
在你開始之前
如果您尚未將 Firebase 添加到您的 Android 項目中,請將其添加到您的 Android 項目中。
在模塊(應用程序級)Gradle 文件(通常
<project>/<app-module>/build.gradle.kts
或<project>/<app-module>/build.gradle
)中,添加 Firebase 身份驗證的依賴項安卓庫。我們建議使用Firebase Android BoM來控制庫版本控制。此外,作為設置 Firebase 身份驗證的一部分,您需要將 Google Play 服務 SDK 添加到您的應用中。
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:32.3.1")) // 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.7.0") }通過使用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.1.2")
// Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:20.7.0") }Java
dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:32.3.1")) // 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.7.0") }通過使用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.1.2")
// Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:20.7.0") }如果您尚未指定應用的 SHA 指紋,請從 Firebase 控制台的“設置”頁面執行此操作。有關如何獲取應用程序的 SHA 指紋的詳細信息,請參閱驗證您的客戶端。
- 在 Firebase 控制台中啟用 Google 作為登錄方法:
- 在Firebase 控制台中,打開“身份驗證”部分。
- 在登錄方法選項卡上,啟用Google登錄方法並單擊保存。
當控制台中出現提示時,下載更新後的 Firebase 配置文件 (
google-services.json
),該文件現在包含 Google 登錄所需的 OAuth 客戶端信息。將此更新後的配置文件移至您的 Android Studio 項目中,替換現已過時的相應配置文件。 (請參閱將 Firebase 添加到您的 Android 項目。)
使用 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 實時數據庫和雲存儲安全規則中,您可以從
auth
變量獲取登錄用戶的唯一用戶 ID,並使用它來控制用戶可以訪問哪些數據。
您可以通過將身份驗證提供程序憑據鏈接到現有用戶帳戶,允許用戶使用多個身份驗證提供程序登錄您的應用程序。
要註銷用戶,請調用signOut
:
Kotlin+KTX
Firebase.auth.signOut()
Java
FirebaseAuth.getInstance().signOut();