您可以使用 Google Play 游戏服务让玩家登录基于 Firebase 构建的 Android 游戏。要通过 Firebase 使用 Google Play 游戏服务登录,请首先使用 Google Play 游戏让玩家登录,然后在执行此操作时请求 OAuth 2.0 授权代码。然后,将授权代码传递给PlayGamesAuthProvider
以生成 Firebase 凭据,您可以使用该凭据向 Firebase 进行身份验证。
在你开始之前
设置您的 Android 项目
如果您还没有,请将 Firebase 添加到您的 Android 项目中。
在您的模块(应用级)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.2.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.1.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.2.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.1.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 项目
从 Firebase 控制台的“设置”页面设置游戏的 SHA-1 指纹。
您可以使用 gradle
signingReport
命令获取签名证书的 SHA 哈希值:./gradlew signingReport
启用 Google Play 游戏作为登录提供商:
查找项目的 Web 服务器客户端 ID 和客户端密码。 Web 服务器客户端 ID 向 Google Play 授权服务器标识您的 Firebase 项目。
要找到这些值:
- 在Google API 控制台凭据页面中打开您的 Firebase 项目。
- 在OAuth 2.0 客户端 ID部分,打开Web 客户端(由 Google 服务自动创建)详细信息页面。此页面列出了您的 Web 服务器客户端 ID 和密码。
然后,在Firebase 控制台中,打开身份验证部分。
在登录方法选项卡上,启用Play 游戏登录提供程序。您将需要指定您从 API 控制台获得的项目的 Web 服务器客户端 ID 和客户端密码。
使用您的 Firebase 应用信息配置 Play 游戏服务
在Google Play Console中,打开您的 Google Play 应用或创建一个。
在发展部分,点击Play 游戏服务 > 设置和管理 > 配置。
点击Yes, my game already uses Google APIs ,从列表中选择您的 Firebase 项目,然后点击Use 。
在 Play 游戏服务配置页面上,单击添加凭据。
- 选择游戏服务器类型。
- 在OAuth 客户端字段中,选择您项目的 Web 客户端 ID。请确保这与您在启用 Play 游戏登录时指定的客户端 ID 相同。
- 保存您的更改。
仍然在 Play 游戏服务配置页面上,再次单击添加凭据。
- 选择安卓类型。
- 在OAuth 客户端字段中,选择您项目的 Android 客户端 ID。 (如果您没有看到您的 Android 客户端 ID,请确保您在 Firebase 控制台中设置了您游戏的 SHA-1 指纹。)
- 保存您的更改。
在测试人员页面上,添加需要在您的游戏发布到 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 帐户凭据。
- 首先,在登录活动的
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 时,检查播放器是否已使用 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.
- 玩家以静默方式或交互方式登录 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();