Firebase is back at Google I/O on May 10! Register now

在 Android 上使用 Google Play 遊戲服務進行身份驗證

透過集合功能整理內容 你可以依據偏好儲存及分類內容。

您可以使用 Google Play 遊戲服務讓玩家登錄基於 Firebase 構建的 Android 遊戲。要通過 Firebase 使用 Google Play 遊戲服務登錄,請首先使用 Google Play 遊戲讓玩家登錄,然後在執行此操作時請求 OAuth 2.0 授權代碼。然後,將授權代碼傳遞給PlayGamesAuthProvider以生成 Firebase 憑據,您可以使用該憑據向 Firebase 進行身份驗證。

在你開始之前

設置您的 Android 項目

  1. 如果您還沒有,請將 Firebase 添加到您的 Android 項目中

  2. 在您的模塊(應用級)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.4.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.2.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.4.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.2.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'
    }

設置您的 Firebase 項目

  1. 從 Firebase 控制台的“設置”頁面設置遊戲的 SHA-1 指紋。

    您可以使用 gradle signingReport命令獲取簽名證書的 SHA 哈希值:

    ./gradlew signingReport

  2. 啟用 Google Play 遊戲作為登錄提供商:

    1. 查找項目的 Web 服務器客戶端 ID 和客戶端密碼。 Web 服務器客戶端 ID 向 Google Play 授權服務器標識您的 Firebase 項目。

      要找到這些值:

      1. Google API 控制台憑據頁面中打開您的 Firebase 項目。
      2. OAuth 2.0 客戶端 ID部分,打開Web 客戶端(由 Google 服務自動創建)詳細信息頁面。此頁面列出了您的 Web 服務器客戶端 ID 和密碼。
    2. 然後,在Firebase 控制台中,打開身份驗證部分。

    3. 登錄方法選項卡上,啟用Play 遊戲登錄提供程序。您將需要指定您從 API 控制台獲得的項目的 Web 服務器客戶端 ID 和客戶端密碼。

使用您的 Firebase 應用信息配置 Play 遊戲服務

  1. Google Play Console中,打開您的 Google Play 應用或創建一個。

  2. 發展部分,點擊Play 遊戲服務 > 設置和管理 > 配置

  3. 點擊Yes, my game already uses Google APIs ,從列表中選擇您的 Firebase 項目,然後點擊Use

  4. 在 Play 遊戲服務配置頁面上,單擊添加憑據

    1. 選擇遊戲服務器類型。
    2. OAuth 客戶端字段中,選擇您項目的 Web 客戶端 ID。請確保這與您在啟用 Play 遊戲登錄時指定的客戶端 ID 相同。
    3. 保存您的更改。
  5. 仍然在 Play 遊戲服務配置頁面上,再次單擊添加憑據

    1. 選擇安卓類型。
    2. OAuth 客戶端字段中,選擇您項目的 Android 客戶端 ID。 (如果您沒有看到您的 Android 客戶端 ID,請確保您在 Firebase 控制台中設置了您遊戲的 SHA-1 指紋。)
    3. 保存您的更改。
  6. 測試人員頁面上,添加需要在您的遊戲發佈到 Play 商店之前能夠登錄您的遊戲的任何用戶的電子郵件地址。

將 Play 遊戲登錄集成到您的遊戲中

首先,將 Play 遊戲登錄集成到您的應用中。有關完整說明,請參閱登錄 Android 遊戲

在您的集成中,當您構建GoogleSignInOptions對象時,使用DEFAULT_GAMES_SIGN_IN配置並調用requestServerAuthCode

Kotlin+KTX

val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
        .requestServerAuthCode(getString(R.string.default_web_client_id))
        .build()

Java

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
        .requestServerAuthCode(getString(R.string.default_web_client_id))
        .build();

您必須將 Web 服務器客戶端 ID 傳遞給requestServerAuthCode方法。這是您在 Firebase 控制台中啟用 Play 遊戲登錄時提供的 ID。

使用 Firebase 進行身份驗證

將 Play 遊戲登錄添加到您的應用後,您需要設置 Firebase 以使用您在玩家成功登錄 Play 遊戲時獲得的 Google 帳戶憑據。

  1. 首先,在登錄活動的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();
  1. 初始化 Activity 時,檢查播放器是否已使用 Firebase 登錄:

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);
}
If the player isn't signed in, present the player with your game's
signed-out experience, including the option to sign in.
  1. 玩家以靜默方式或交互方式登錄 Play Games 後,從GoogleSignInAccount對象獲取授權代碼,將其交換為 Firebase 憑據,並使用 Firebase 憑據通過 Firebase 進行身份驗證:

Kotlin+KTX

// Call this both in the silent sign-in task's OnCompleteListener and in the
// Activity's onActivityResult handler.
private fun firebaseAuthWithPlayGames(acct: GoogleSignInAccount) {
    Log.d(TAG, "firebaseAuthWithPlayGames:" + acct.id!!)

    val auth = Firebase.auth
    val credential = PlayGamesAuthProvider.getCredential(acct.serverAuthCode!!)
    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)
                    Toast.makeText(baseContext, "Authentication failed.",
                            Toast.LENGTH_SHORT).show()
                    updateUI(null)
                }

                // ...
            }
}

Java

// Call this both in the silent sign-in task's OnCompleteListener and in the
// Activity's onActivityResult handler.
private void firebaseAuthWithPlayGames(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithPlayGames:" + acct.getId());

    final FirebaseAuth auth = FirebaseAuth.getInstance();
    AuthCredential credential = PlayGamesAuthProvider.getCredential(acct.getServerAuthCode());
    auth.signInWithCredential(credential)
            .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 = auth.getCurrentUser();
                        updateUI(user);
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(MainActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();
                        updateUI(null);
                    }

                    // ...
                }
            });
}

如果對signInWithCredential的調用成功,您可以使用getCurrentUser方法獲取用戶的帳戶數據。

下一步

用戶首次登錄後,系統會創建一個新用戶帳戶並將其鏈接到他們的 Play 遊戲 ID。這個新帳戶存儲為您的 Firebase 項目的一部分,可用於在您項目中的每個應用程序中識別用戶。

在您的遊戲中,您可以從FirebaseUser對象獲取用戶的 Firebase UID:

Kotlin+KTX

val user = auth.currentUser
user?.let {
    val playerName = it.displayName

    // The user's Id, unique to the Firebase project.
    // Do NOT use this value to authenticate with your backend server, if you
    // have one; use FirebaseUser.getIdToken() instead.
    val uid = it.uid
}

Java

FirebaseUser user = mAuth.getCurrentUser();
String playerName = user.getDisplayName();

// The user's Id, unique to the Firebase project.
// Do NOT use this value to authenticate with your backend server, if you
// have one; use FirebaseUser.getIdToken() instead.
String uid = user.getUid();

在您的 Firebase 實時數據庫和雲存儲安全規則中,您可以從auth變量中獲取登錄用戶的唯一用戶 ID,並使用它來控制用戶可以訪問的數據。

要獲取用戶的 Play 遊戲玩家信息或訪問 Play 遊戲服務,請使用Google Play 遊戲 SDK提供的 API。

要註銷用戶,請調用FirebaseAuth.signOut()

Kotlin+KTX

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();