אימות באמצעות Google Play Games Services ב-Android

אתם יכולים להשתמש בשירותי Google Play Games כדי להכניס שחקנים למשחק Android שמבוסס על Firebase. כדי להשתמש בכניסה ל-Google Play Games באמצעות Firebase, קודם צריך להכניס את השחקן ל-Google Play Games ולבקש קוד אימות OAuth 2.0. אחר כך מעבירים את קוד האימות אל PlayGamesAuthProvider כדי ליצור פרטי כניסה ל-Firebase, שאפשר להשתמש בהם לאימות ב-Firebase.

לפני שמתחילים

הגדרת פרויקט Android

  1. אם עדיין לא עשיתם זאת, אתם צריכים להוסיף את Firebase לפרויקט Android.

  2. בקובץ Gradle של המודול (ברמת האפליקציה) (בדרך כלל <project>/<app-module>/build.gradle.kts או <project>/<app-module>/build.gradle), מוסיפים את התלות בספריית Firebase Authentication ל-Android. מומלץ להשתמש ב-Firebase Android BoM כדי לשלוט בניהול הגרסאות של הספריות.

    בנוסף, במסגרת ההגדרה של Firebase Authentication, צריך להוסיף את Google Play services SDK לאפליקציה.

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

הגדרת פרויקט Firebase

  1. מגדירים את טביעת האצבע של SHA-1 במשחק בדף Settings במסוף Firebase.

    אפשר לקבל את הגיבוב SHA של אישור החתימה באמצעות הפקודה gradle signingReport:

    ./gradlew signingReport

  2. הפעלת Google Play Games כספק כניסה:

    1. מאתרים את מזהה הלקוח ואת הסוד של הלקוח של שרת האינטרנט של הפרויקט. מזהה הלקוח של שרת האינטרנט מזהה את פרויקט Firebase בשרתי האימות של Google Play.

      כדי למצוא את הערכים האלה:

      1. פותחים את פרויקט Firebase בדף פרטי הכניסה של Google APIs console.
      2. בקטע מזהי לקוחות OAuth 2.0, פותחים את דף הפרטים של לקוח אינטרנט (נוצר אוטומטית על ידי שירות Google). בדף הזה מפורטים מזהה הלקוח והסוד של שרת האינטרנט.
    2. לאחר מכן, במסוף Firebase, פותחים את הקטע אימות.

    3. בכרטיסייה Sign in method (שיטת כניסה), מפעילים את ספק הכניסה Play Games. תצטרכו לציין את מזהה הלקוח ואת סוד הלקוח של שרת האינטרנט של הפרויקט, שקיבלתם מ-APIs console.

הגדרת Play Games services עם פרטי האפליקציה ב-Firebase

  1. במסוף Google Play, פותחים את אפליקציית Google Play או יוצרים אחת.

  2. בקטע צמיחה, לוחצים על Play Games services > הגדרה וניהול > הגדרות.

  3. לוחצים על כן, המשחק שלי כבר עושה שימוש ב-Google APIs, בוחרים את הפרויקט ב-Firebase מהרשימה ולוחצים על שימוש.

  4. בדף ההגדרה של Play Games services, לוחצים על הוספת פרטי כניסה.

    1. בוחרים בסוג שרת המשחקים.
    2. בשדה לקוח OAuth, בוחרים את מזהה לקוח האינטרנט של הפרויקט. חשוב לוודא שזהו אותו מספר לקוח שציינתם כשמפעילים את הכניסה לחשבון Play Games.
    3. שומרים את השינויים.
  5. עדיין בדף ההגדרה של Play Games services, לוחצים שוב על Add Credential.

    1. בוחרים בסוג Android.
    2. בשדה לקוח OAuth, בוחרים את מזהה הלקוח של Android בפרויקט. (אם מזהה הלקוח של Android לא מופיע, צריך לוודא שהגדרתם את טביעת האצבע של SHA-1 של המשחק בFirebase).
    3. שומרים את השינויים.
  6. בדף בודקים, מוסיפים את כתובות האימייל של כל המשתמשים שצריכים להיות מסוגלים להיכנס למשחק לפני שמפרסמים אותו ב-Play Store.

שילוב של כניסה ל-Play Games במשחק

קודם צריך לשלב את הכניסה ל-Play Games באפליקציה. הוראות מלאות זמינות במאמר בנושא כניסה למשחקי Android.

כשיוצרים את האובייקט GoogleSignInOptions בשילוב, משתמשים בהגדרה DEFAULT_GAMES_SIGN_IN ומפעילים את הפונקציה requestServerAuthCode:

Kotlin

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();

צריך להעביר את מזהה הלקוח של שרת האינטרנט אל השיטה requestServerAuthCode. זהו המזהה שסיפקתם כשפעלתם את הכניסה ל-Play Games במסוף Firebase.

אימות באמצעות Firebase

אחרי שמוסיפים לאפליקציה את האפשרות להיכנס באמצעות Play Games, צריך להגדיר את Firebase כך שישתמש בהרשאות של חשבון Google שמתקבלות כששחקן נכנס בהצלחה באמצעות Play Games.

  1. קודם כל, ב-method onCreate של פעילות הכניסה, מקבלים את המופע המשותף של אובייקט FirebaseAuth:

Kotlin

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

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

// 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 Games. החשבון החדש הזה נשמר כחלק מפרויקט Firebase, ואפשר להשתמש בו כדי לזהות משתמש בכל אפליקציה בפרויקט.

במשחק, אפשר לקבל את ה-UID של המשתמש ב-Firebase מהאובייקט FirebaseUser:

Kotlin

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 Realtime Database ו-Cloud Storage, אפשר לקבל את מזהה המשתמש הייחודי של המשתמש המחובר מהמשתנה auth ולהשתמש בו כדי לקבוע לאילו נתונים המשתמש יכול לגשת.

כדי לקבל את פרטי השחקן של משתמש ב-Play Games או לגשת לשירותי Play Games, צריך להשתמש בממשקי ה-API שמסופקים על ידי Google Play Games SDK.

כדי להוציא משתמש מהחשבון, קוראים ל-FirebaseAuth.signOut():

Kotlin

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();