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

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

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

כדי להשתמש בכניסה באמצעות Google Play Games services עם 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:35.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:22.0.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:25.0.0")
    // Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:22.0.0")
    }

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

  1. במסוף Firebase, נכנסים לאבטחה > אימות.

  2. בכרטיסייה הגדרות, מגדירים את טביעת האצבע SHA-1 של המשחק.

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

    ./gradlew signingReport

  3. מפעילים את Google Play Games כספק כניסה:

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

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

      1. פותחים את פרויקט Firebase בדף פרטי הכניסה במסוף Google APIs.
      2. בקטע OAuth 2.0 client IDs, פותחים את דף הפרטים של Web client (auto created by Google Service). בדף הזה מופיעים מזהה הלקוח והסוד של שרת האינטרנט.
    2. חוזרים למסוף Firebase ונכנסים אל אבטחה > אימות.

    3. בכרטיסייה שיטת התחברות, מפעילים את ספק הכניסה Play Games. תצטרכו לציין את מזהה הלקוח וסוד הלקוח של שרת האינטרנט של הפרויקט, שקיבלתם ממסוף Google Cloud.

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

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

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

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

  4. בדף ההגדרות של Play Games services, לוחצים על Add Credential.

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

צריך להעביר את מזהה הלקוח של שרת האינטרנט ל-method‏ 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();
  2. כשמפעילים את הפעילות, בודקים אם השחקן כבר מחובר ל-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);
    }

    אם השחקן לא מחובר לחשבון, הציגו לו את חוויית המשחק ללא חיבור לחשבון, כולל האפשרות להיכנס לחשבון.

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

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

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

כדי להוציא משתמש מהחשבון, מפעילים את FirebaseAuth.signOut:

Kotlin

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();