Uwierzytelniaj przez Google na Androidzie

Możesz zezwolić użytkownikom na uwierzytelnianie w Firebase za pomocą kont Google, integrując Logowanie przez Google z aplikacją.

Aby uzyskać pomoc AI, skopiuj poniższy prompt do agenta kodowania AI (takiego jak Gemini w Android Studio, Antigravity, Claude Code, Codex czy Cursor). Możesz dostosować prompta i wprowadzać zmiany z agentem. Szczegółowe informacje o instalacji znajdziesz w artykule Umiejętności agenta 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.

Zanim zaczniesz

  1. Dodaj Firebase do projektu aplikacji na Androida, jeśli nie korzystasz w nim jeszcze z tej usługi.

  2. W pliku Gradle modułu (na poziomie aplikacji) (zwykle <project>/<app-module>/build.gradle.kts lub <project>/<app-module>/build.gradle) dodaj zależność dla biblioteki Firebase Authentication na Androida. Zalecamy używanie Firebase Android BoM do kontrolowania wersji biblioteki.

    W ramach konfigurowania Firebase Authentication musisz też dodać do aplikacji pakiet 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")
    }

    Gdy korzystasz z Firebase Android BoM, aplikacja zawsze używa zgodnych wersji bibliotek Firebase na Androida.

    (Alternatywa)  Dodaj zależności biblioteki Firebase bez używania BoM

    Jeśli nie zdecydujesz się na użycie Firebase BoM, musisz określić każdą wersję biblioteki Firebase w jej linii zależności.

    Pamiętaj, że jeśli w aplikacji używasz kilku bibliotek Firebase, zdecydowanie zalecamy korzystanie z BoM do zarządzania wersjami bibliotek, co zapewni zgodność wszystkich wersji.

    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. Podaj odcisk cyfrowy SHA-1 aplikacji, jeśli jeszcze nie został podany.

    1. W konsoli Firebase otwórz Ustawienia > karta Ogólne.

    2. Przewiń w dół do karty Twoje aplikacje, wybierz aplikację na Androida i dodaj odcisk cyfrowy SHA-1 w polu Odciski cyfrowe certyfikatu SHA.

    Szczegółowe informacje o tym, jak uzyskać odcisk cyfrowy SHA aplikacji, znajdziesz w artykule na temat uwierzytelniania klienta.

  4. Włącz Google jako dostawcę logowania w projekcie w Firebase:
    1. W konsoli Firebase otwórz Zabezpieczenia > Uwierzytelnianie.
    2. Na karcie Metoda logowania włącz dostawcę logowania Google.
    3. Kliknij Zapisz.
  5. Zaktualizuj plik konfiguracji Firebase.

    1. Gdy pojawi się prośba w konsoli Firebase, pobierz zaktualizowany plik konfiguracji Firebase (google-services.json), który zawiera teraz informacje o kliencie OAuth wymagane do logowania się przez Google.

    2. Przenieś ten zaktualizowany plik konfiguracji do projektu Android Studio, zastępując nim nieaktualny plik konfiguracji. (patrz Dodawanie Firebase do projektu aplikacji na Androida).

Uwierzytelnianie za pomocą Firebase

  1. Zintegruj funkcję Zaloguj się przez Google ze swoją aplikacją, wykonując czynności opisane w dokumentacji Credential Managera. Oto ogólne instrukcje:
    1. Utwórz instancję żądania logowania przez Google za pomocą GetGoogleIdOption. Następnie utwórz żądanie Credential Managera za pomocą 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();

      W żądaniu powyżej musisz przekazać identyfikator klienta „serwera” do metody setServerClientId. Aby znaleźć identyfikator klienta OAuth 2.0:

      1. Otwórz stronę Dane logowania w konsoli Google Cloud.
      2. Identyfikator klienta typu Aplikacja internetowa to identyfikator klienta OAuth 2.0 serwera backendu.
    2. Sprawdź, czy po zintegrowaniu funkcji Zaloguj się przez Google aktywność związana z logowaniem zawiera kod podobny do tego:

      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. W metodzie onCreate aktywności logowania pobierz udostępnioną instancję obiektu FirebaseAuth:

    Kotlin

    private lateinit var auth: FirebaseAuth
    // ...
    // Initialize Firebase Auth
    auth = Firebase.auth

    Java

    private FirebaseAuth mAuth;
    // ...
    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
  3. Podczas inicjowania aktywności sprawdź, czy użytkownik jest obecnie zalogowany:

    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. Teraz pobierz token identyfikacji Google użytkownika utworzony w kroku 1, wymień go na dane logowania Firebase i uwierzytelnij się w Firebase za pomocą tych danych:

    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);
                    }
                });
    }
    Jeśli wywołanie metody signInWithCredential się powiedzie, możesz użyć metody getCurrentUser, aby uzyskać dane konta użytkownika.

Dalsze kroki

Gdy użytkownik zaloguje się po raz pierwszy, zostanie utworzone nowe konto użytkownika i połączone z danymi logowania, czyli nazwą użytkownika i hasłem, numerem telefonu lub informacjami o dostawcy uwierzytelniania, za pomocą których użytkownik się zalogował. To nowe konto jest przechowywane w projekcie Firebase i może służyć do identyfikowania użytkownika we wszystkich aplikacjach w projekcie, niezależnie od tego, jak się loguje.

  • W aplikacjach możesz uzyskać podstawowe informacje o profilu użytkownika z obiektu FirebaseUser. Zobacz Zarządzanie użytkownikami.

  • W Firebase Realtime Database i Cloud Storageregułach zabezpieczeń możesz pobrać unikalny identyfikator zalogowanego użytkownika ze zmiennej auth i użyć go do kontrolowania, do jakich danych użytkownik ma dostęp.

Możesz zezwolić użytkownikom na logowanie się w aplikacji przy użyciu wielu dostawców uwierzytelniania, łącząc dane logowania dostawcy uwierzytelniania z istniejącym kontem użytkownika.

Aby wylogować użytkownika, wywołaj signOut. Musisz też wyczyścić bieżący stan danych logowania użytkownika u wszystkich dostawców danych logowania, zgodnie z zaleceniami zawartymi w dokumentacji Menedżera danych logowania:

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