אימות עם Google ב-Android

אתם יכולים לאפשר למשתמשים לבצע אימות ב-Firebase באמצעות חשבונות Google שלהם על ידי שילוב של "כניסה באמצעות חשבון Google" באפליקציה.

כדי לקבל עזרה מ-AI, מעתיקים את ההנחיה שבהמשך אל סוכן ה-AI לתכנות (כמו Gemini ב-Android Studio,‏ Antigravity,‏ Claude Code,‏ Codex ו-Cursor). אתם יכולים להתאים אישית את ההנחיה ולשפר את הסוכן. מידע מפורט על ההתקנה זמין בדף סקילים אג'נטיים ב-Firebase.

Help me use Firebase in my app.
1. Make sure that **Firebase agent skills** are installed and updated. For Claude Code, Codex, or Cursor agents, help me install the Firebase plugin. For other agents, run `npx skills add firebase/agent-skills`. Always try to use **Firebase agent skills** for Firebase-related tasks.
2. Help me set up and use Firebase Authentication with Google Sign-In in my app.

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

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

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

    בנוסף, כחלק מההגדרה של Firebase Authentication, צריך להוסיף לאפליקציה את ה-SDK של Credential Manager.

    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 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.

    (אפשרות חלופית)  הוספת תלויות של ספריית 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 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")
    }

  3. אם עדיין לא עשיתם את זה, ציינו את טביעת האצבע בפורמט SHA-1 של האפליקציה.

    1. במסוף Firebase, נכנסים לכרטיסייה הגדרות > כללי.

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

    במאמר אימות הלקוח מוסבר איך לקבל את טביעת האצבע של SHA של האפליקציה.

  4. מפעילים את Google כספק כניסה לפרויקט ב-Firebase:
    1. במסוף Firebase, נכנסים אל אבטחה > אימות.
    2. בכרטיסייה שיטת התחברות, מפעילים את ספק הכניסה Google.
    3. לוחצים על שמירה.
  5. מעדכנים את קובץ התצורה של Firebase.

    1. כשמוצגת בקשה במסוף Firebase, מורידים את קובץ התצורה המעודכן של Firebase‏ (google-services.json), שמכיל עכשיו את פרטי לקוח ה-OAuth שנדרשים לכניסה באמצעות חשבון Google.

    2. מעבירים את קובץ התצורה המעודכן לפרויקט ב-Android Studio, ומחליפים את קובץ התצורה התואם שכבר לא עדכני. (איך מוסיפים את Firebase לפרויקט Android)

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

  1. כדי לשלב את התכונה "כניסה באמצעות חשבון Google" באפליקציה, פועלים לפי השלבים שמפורטים במסמכי התיעוד של Credential Manager. הנה ההוראות הכלליות:
    1. יוצרים מופע של בקשת כניסה באמצעות חשבון Google באמצעות GetGoogleIdOption. אחר כך יוצרים את הבקשה ל-Credential Manager באמצעות GetCredentialRequest:

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

      בבקשה שלמעלה, צריך להעביר את מזהה הלקוח של השרת ל-method‏ setServerClientId. כדי למצוא את מזהה הלקוח ב-OAuth 2.0:

      1. פותחים את הדף Credentials במסוף Google Cloud.
      2. מזהה הלקוח מסוג אפליקציית אינטרנט הוא מזהה הלקוח ב-OAuth 2.0 של שרת הקצה העורפי.
    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. ב-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();
  3. כשמאתחלים את הפעילות, בודקים אם המשתמש מחובר כרגע:

    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. עכשיו מקבלים את הטוקן של מזהה Google של המשתמש שנוצר בשלב 1, מחליפים אותו בפרטי כניסה ל-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 מצליחה, אפשר להשתמש ב-method‏ getCurrentUser כדי לקבל את נתוני החשבון של המשתמש.

השלבים הבאים

אחרי שמשתמש נכנס לחשבון בפעם הראשונה, נוצר חשבון משתמש חדש שמקושר לפרטי הכניסה – כלומר, שם המשתמש והסיסמה, מספר הטלפון או פרטי ספק האימות – שאיתם המשתמש נכנס לחשבון. החשבון החדש הזה נשמר כחלק מהפרויקט ב-Firebase, ואפשר להשתמש בו כדי לזהות משתמש בכל אפליקציה בפרויקט, בלי קשר לאופן שבו המשתמש נכנס לחשבון.

  • באפליקציות, אפשר לקבל את פרטי הפרופיל הבסיסיים של המשתמש מהאובייקט FirebaseUser. מידע נוסף זמין במאמר ניהול משתמשים.

  • בכללי האבטחה של Firebase Realtime Database ו-Cloud Storage, אפשר לקבל את מזהה המשתמש הייחודי של המשתמש המחובר מהמשתנה auth, ולהשתמש בו כדי לקבוע לאילו נתונים המשתמש יכול לגשת.

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

כדי להוציא משתמש מהחשבון, מפעילים את 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());
                }
            });
}