使用 Google 账号进行身份验证 (Android)

您可以让用户使用自己的 Google 账号进行 Firebase 身份验证。

准备工作

  1. 将 Firebase 添加到您的 Android 项目(如果尚未添加)。

  2. 模块(应用级)Gradle 文件(通常是 <project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle)中,添加 Firebase Authentication 库的依赖项。我们建议使用 Firebase Android BoM 来实现库版本控制。

    此外,在设置 Firebase Authentication 时,您还需要将 Credential Manager SDK 添加到您的应用中。

    dependencies {     // Import the BoM for the Firebase platform     implementation(platform("com.google.firebase:firebase-bom:33.15.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 dependencies for the Credential Manager libraries and specify their versions implementation("androidx.credentials:credentials:1.3.0") implementation("androidx.credentials:credentials-play-services-auth:1.3.0") implementation("com.google.android.libraries.identity.googleid:googleid:1.1.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:23.2.1")
    // Also add the dependencies for the Credential Manager libraries and specify their versions implementation("androidx.credentials:credentials:1.3.0") implementation("androidx.credentials:credentials-play-services-auth:1.3.0") implementation("com.google.android.libraries.identity.googleid:googleid:1.1.1")
    }
    是否想要查找 Kotlin 专用的库模块?2023 年 10 月 (Firebase BoM 32.5.0) 开始,Kotlin 和 Java 开发者可以依赖于主库模块(如需了解详情,请参阅关于此计划的常见问题解答)。

  3. 如果您尚未指定应用的 SHA 指纹,请在 Firebase 控制台的设置页面中指定。 如需详细了解如何获取您的应用的 SHA 指纹,请参阅对客户端进行身份验证

  4. Firebase 控制台中启用 Google 登录方法:
    1. Firebase 控制台中,打开 Auth 部分。
    2. 登录方法标签页中,启用 Google 登录方法并点击保存
  5. 在控制台中出现提示时,下载更新后的 Firebase 配置文件 (google-services.json),该文件现在包含进行 Google 登录所需的 OAuth 客户端信息。

  6. 将此更新后的配置文件转移到您的 Android Studio 项目中,替换掉现已过时的相应配置文件。(请参阅将 Firebase 添加到您的 Android 项目。)

进行 Firebase 身份验证

  1. 按照 Credential Manager 文档中的步骤,将“使用 Google 账号登录”功能集成到您的应用中。以下是简要说明:
    1. 使用 GetGoogleIdOption 实例化 Google 登录请求。然后,使用 GetCredentialRequest 创建 Credential Manager 请求:

      Kotlin

      // Instantiate a Google sign-in request val googleIdOption = GetGoogleIdOption.Builder()     // 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()  // Create the Credential Manager request val request = GetCredentialRequest.Builder()     .addCredentialOption(googleIdOption)     .build()

      Java

      // Instantiate a Google sign-in request GetGoogleIdOption googleIdOption = new GetGoogleIdOption.Builder()         .setFilterByAuthorizedAccounts(true)         .setServerClientId(getString(R.string.default_web_client_id))         .build();  // Create the Credential Manager request GetCredentialRequest request = new GetCredentialRequest.Builder()         .addCredentialOption(googleIdOption)         .build();

      在上面的请求中,您必须将“服务器”客户端 ID 传递给 setServerClientId 方法。如需查找 OAuth 2.0 客户端 ID,请执行以下操作:

      1. Google Cloud 控制台中打开凭据页面
      2. Web 应用类型的客户端 ID 是后端服务器的 OAuth 2.0 客户端 ID。
    2. 检查集成“使用 Google 账号登录”功能后,您的登录活动的代码是否如下所示:

      Kotlin

      private fun handleSignIn(credential: Credential) {     // Check if credential is of type Google ID     if (credential is CustomCredential && credential.type == TYPE_GOOGLE_ID_TOKEN_CREDENTIAL) {         // Create Google ID Token         val googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credential.data)          // Sign in to Firebase with using the token         firebaseAuthWithGoogle(googleIdTokenCredential.idToken)     } else {         Log.w(TAG, "Credential is not of type Google ID!")     } }

      Java

      private void handleSignIn(Credential credential) {     // Check if credential is of type Google ID     if (credential instanceof CustomCredential customCredential             && credential.getType().equals(TYPE_GOOGLE_ID_TOKEN_CREDENTIAL)) {         // Create Google ID Token         Bundle credentialData = customCredential.getData();         GoogleIdTokenCredential googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credentialData);          // Sign in to Firebase with using the token         firebaseAuthWithGoogle(googleIdTokenCredential.getIdToken());     } else {         Log.w(TAG, "Credential is not of type Google ID!");     } }
  2. 在登录 Activity 的 onCreate 方法中,获取 FirebaseAuth 对象的共享实例:

    Kotlin

    private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth

    Java

    private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
  3. 初始化 Activity 时,请检查用户当前是否已登录:

    Kotlin

    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. 现在,获取第 1 步中创建的用户 Google ID 令牌,用其换取 Firebase 凭据,然后使用此 Firebase 凭据进行 Firebase 身份验证:

    Kotlin

    private fun firebaseAuthWithGoogle(idToken: String) {     val credential = GoogleAuthProvider.getCredential(idToken, null)     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)                 updateUI(null)             }         } }

    Java

    private void firebaseAuthWithGoogle(String idToken) {     AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);     mAuth.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");                     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 DatabaseCloud Storage 安全规则中,您可以从 auth 变量获取已登录用户的唯一用户 ID,然后利用此 ID 来控制用户可以访问哪些数据。

您可以通过将身份验证提供方凭据关联至现有用户账号,让用户可以使用多个身份验证提供方登录您的应用。

如需将用户退出登录,请调用 signOut。 您还需要清除所有凭据提供程序的当前用户凭据状态,如 Credential Manager 文档中所建议:

Kotlin

private fun signOut() {     // Firebase sign out     auth.signOut()      // When a user signs out, clear the current user credential state from all credential providers.     lifecycleScope.launch {         try {             val clearRequest = ClearCredentialStateRequest()             credentialManager.clearCredentialState(clearRequest)             updateUI(null)         } catch (e: ClearCredentialException) {             Log.e(TAG, "Couldn't clear user credentials: ${e.localizedMessage}")         }     } }

Java

private void signOut() {     // Firebase sign out     mAuth.signOut();      // When a user signs out, clear the current user credential state from all credential providers.     ClearCredentialStateRequest clearRequest = new ClearCredentialStateRequest();     credentialManager.clearCredentialStateAsync(             clearRequest,             new CancellationSignal(),             Executors.newSingleThreadExecutor(),             new CredentialManagerCallback<>() {                 @Override                 public void onResult(@NonNull Void result) {                     updateUI(null);                 }                  @Override                 public void onError(@NonNull ClearCredentialException e) {                     Log.e(TAG, "Couldn't clear user credentials: " + e.getLocalizedMessage());                 }             }); }