在 Android 上透過 Google 驗證

您可以讓使用者使用自己的 Google 帳戶向 Firebase 進行驗證。

事前準備

  1. 如果您尚未將 Firebase 新增至 Android 專案,請先完成這項作業。

  2. 模組 (應用程式層級) Gradle 檔案 (通常是 <project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle) 中,新增 Android 專用 Firebase 驗證程式庫的依附元件。建議您使用 Firebase Android BoM 控管程式庫的版本管理。

    此外,設定 Firebase 驗證時,您必須將 Google Play 服務 SDK 新增至您的應用程式。

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:33.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")
    // Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:21.2.0")
    }

    只要使用 Firebase Android BoM,您的應用程式就會一律使用相容的 Firebase Android 程式庫版本。

    (替代做法) 新增 Firebase 程式庫依附元件,「不」使用 BoM

    如果選擇不使用 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:23.0.0")
    // Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:21.2.0")
    }
    在尋找 Kotlin 專用的程式庫模組嗎?2023 年 10 月 (Firebase BoM 32.5.0) 起,Kotlin 和 Java 開發人員都能使用主要的程式庫模組 (詳情請參閱這項計畫的常見問題)。

  3. 如果尚未指定應用程式的 SHA 指紋,請前往 Firebase 控制台的「設定」頁面指定。如要進一步瞭解如何取得應用程式的 SHA 指紋,請參閱「驗證用戶端」。

  4. 在 Firebase 控制台中啟用 Google 做為登入方式:
    1. Firebase 控制台開啟「驗證」專區。
    2. 在「Sign in method」分頁中啟用「Google」登入方式,然後按一下「Save」
  5. 如果主控台顯示提示,請下載更新後的 Firebase 設定檔 (google-services.json),其中包含 Google 登入所需的 OAuth 用戶端資訊。

  6. 將這個更新後的設定檔移至 Android Studio 專案,取代過時的對應設定檔。(請參閱「將 Firebase 新增至 Android 專案」)。

透過 Firebase 驗證

  1. 按照讓使用者利用已儲存的憑證登入頁面的步驟操作,將 Google One Tap 登入機制整合至應用程式。設定 BeginSignInRequest 物件時,請呼叫 setGoogleIdTokenRequestOptions

    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();
        
    您必須將「伺服器」用戶端 ID 傳遞至 setGoogleIdTokenRequestOptions 方法。如何找出 OAuth 2.0 用戶端 ID:
    1. 在 GCP 主控台中開啟「Credentials」(憑證) 頁面
    2. 網頁應用程式類型的用戶端 ID 是後端伺服器的 OAuth 2.0 用戶端 ID。
    整合 Google 登入功能後,您的登入活動會有類似下列的程式碼:

    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;
          }
      }
    }
    
  2. 在登入活動的 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();
  3. 初始化「活動」時,請檢查使用者目前是否登入:

    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);
    }
  4. 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 即時資料庫和 Cloud Storage 安全性規則中,您可以透過 auth 變數取得登入使用者的專屬 ID,並使用該 ID 控管使用者可存取哪些資料。

您可以將驗證供應商憑證連結至現有的使用者帳戶,讓使用者透過多個驗證服務提供者登入您的應用程式。

如要登出使用者,請呼叫 signOut

Kotlin+KTX

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();