您可以讓使用者使用其 Google 帳號透過 Firebase 進行身份驗證。
在你開始之前
如果您尚未將 Firebase 新增至您的 Android 專案中,請將其新增至您的 Android 專案中。
在模組(應用程式層級)Gradle 檔案(通常
<project>/<app-module>/build.gradle.kts
或<project>/<app-module>/build.gradle
)中,新增Firebase 驗證的依賴項Android 的庫。我們建議使用Firebase Android BoM來控制函式庫版本控制。此外,作為設定 Firebase 驗證的一部分,您需要將 Google Play 服務 SDK 新增至您的應用程式。
dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:32.6.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.7.0") }透過使用Firebase Android BoM ,您的應用程式將始終使用 Firebase Android 程式庫的相容版本。
正在尋找 Kotlin 特定的庫模組?從2023 年 10 月(Firebase BoM 32.5.0)開始,Kotlin 和 Java 開發人員都可以依賴主庫模組(有關詳細信息,請參閱有關此計劃的常見問題解答)。(替代方法)在不使用 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.3.0")
// 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();