Firebase is back at Google I/O on May 10! Register now

Uwierzytelnij za pomocą Google na Androida, Uwierzytelnij za pomocą Google na Androida

Zadbaj o dobrą organizację dzięki kolekcji Zapisuj i kategoryzuj treści zgodnie ze swoimi preferencjami.

Możesz zezwolić użytkownikom na uwierzytelnianie w Firebase przy użyciu ich kont Google.

Zanim zaczniesz

  1. Jeśli jeszcze tego nie zrobiłeś, dodaj Firebase do swojego projektu na Androida .

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

    Ponadto w ramach konfigurowania uwierzytelniania Firebase musisz dodać do swojej aplikacji pakiet SDK usług Google Play.

    Kotlin+KTX

    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:31.2.3')
    
        // 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'
    }

    Korzystając z Firebase Android BoM , Twoja aplikacja będzie zawsze korzystać ze zgodnych wersji bibliotek Firebase Android.

    (Alternatywnie) Dodaj zależności biblioteki Firebase bez korzystania z BoM

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

    Pamiętaj, że jeśli używasz w swojej aplikacji wielu bibliotek Firebase, zdecydowanie zalecamy korzystanie z BoM do zarządzania wersjami bibliotek, co zapewnia 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-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.3')
    
        // 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'
    }

    Korzystając z Firebase Android BoM , Twoja aplikacja będzie zawsze korzystać ze zgodnych wersji bibliotek Firebase Android.

    (Alternatywnie) Dodaj zależności biblioteki Firebase bez korzystania z BoM

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

    Pamiętaj, że jeśli używasz w swojej aplikacji wielu bibliotek Firebase, zdecydowanie zalecamy korzystanie z BoM do zarządzania wersjami bibliotek, co zapewnia 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: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'
    }

  3. Jeśli nie określiłeś jeszcze odcisku palca SHA-1 swojej aplikacji, zrób to na stronie Ustawienia w konsoli Firebase. Zapoznaj się z artykułem Uwierzytelnianie klienta , aby uzyskać szczegółowe informacje na temat uzyskiwania odcisku palca SHA-1 aplikacji.

  4. Włącz Google jako metodę logowania w konsoli Firebase:
    1. W konsoli Firebase otwórz sekcję Auth .
    2. Na karcie Metoda logowania włącz metodę logowania Google i kliknij Zapisz .

Uwierzytelnij w Firebase

  1. Zintegruj logowanie Google One Tap ze swoją aplikacją, wykonując czynności opisane na stronie Logowanie użytkowników za pomocą zapisanych danych logowania . Podczas konfigurowania obiektu BeginSignInRequest wywołaj setGoogleIdTokenRequestOptions :

    Kotlin+KTX

    signInRequest = BeginSignInRequest.builder()
                .setGoogleIdTokenRequestOptions(
                    BeginSignInRequest.GoogleIdTokenRequestOptions.builder()
                        .setSupported(true)
                        // Your server's client ID, not your Android client ID.
                        .setServerClientId(getString(R.string.your_web_client_id))
                        // Only show accounts previously used to sign in.
                        .setFilterByAuthorizedAccounts(true)
                        .build())
                .build()
    

    Java

    signInRequest = BeginSignInRequest.builder()
        .setGoogleIdTokenRequestOptions(GoogleIdTokenRequestOptions.builder()
                .setSupported(true)
                // 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())
        .build();
        
    Musisz przekazać identyfikator klienta „serwera” do metody setGoogleIdTokenRequestOptions . Aby znaleźć identyfikator klienta OAuth 2.0:
    1. Otwórz stronę Poświadczenia w konsoli GCP.
    2. Identyfikator klienta typu aplikacji internetowej to identyfikator klienta OAuth 2.0 serwera zaplecza.
    Po zintegrowaniu usługi Google Sign-In aktywność związana z logowaniem ma kod podobny do następującego:

    Kotlin+KTX

    class YourActivity : AppCompatActivity() {
    
        // ...
        private val REQ_ONE_TAP = 2  // Can be any integer unique to the Activity
        private var showOneTapUI = true
        // ...
    
        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            super.onActivityResult(requestCode, resultCode, data)
    
            when (requestCode) {
                 REQ_ONE_TAP -> {
                    try {
                        val credential = oneTapClient.getSignInCredentialFromIntent(data)
                        val idToken = credential.googleIdToken
                        when {
                            idToken != null -> {
                                // Got an ID token from Google. Use it to authenticate
                                // with Firebase.
                                Log.d(TAG, "Got ID token.")
                            }
                            else -> {
                                // Shouldn't happen.
                                Log.d(TAG, "No ID token!")
                            }
                        }
                    } catch (e: ApiException) {
                        // ...
                }
            }
        }
        // ...
    }
    

    Java

    public class YourActivity extends AppCompatActivity {
    
      // ...
      private static final int REQ_ONE_TAP = 2;  // Can be any integer unique to the Activity.
      private boolean showOneTapUI = true;
      // ...
    
      @Override
      protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
    
          switch (requestCode) {
              case REQ_ONE_TAP:
                  try {
                      SignInCredential credential = oneTapClient.getSignInCredentialFromIntent(data);
                      String idToken = credential.getGoogleIdToken();
                      if (idToken !=  null) {
                          // Got an ID token from Google. Use it to authenticate
                          // with Firebase.
                          Log.d(TAG, "Got ID token.");
                      }
                  } catch (ApiException e) {
                      // ...
                  }
                  break;
          }
      }
    }
    
  2. W metodzie onCreate aktywności związanej z logowaniem pobierz udostępnioną instancję obiektu FirebaseAuth :

    Kotlin+KTX

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

    Java

    private FirebaseAuth mAuth;
    // ...
    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();
  3. Podczas inicjowania działania sprawdź, czy użytkownik jest aktualnie zalogowany:

    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);
    }
  4. W swoim module obsługi onActivityResult() (patrz krok 1) uzyskaj token identyfikatora Google użytkownika, wymień go na poświadczenie Firebase i uwierzytelnij się w Firebase przy użyciu poświadczenia Firebase:

    Kotlin+KTX

    val googleCredential = oneTapClient.getSignInCredentialFromIntent(data)
    val idToken = googleCredential.googleIdToken
    when {
        idToken != null -> {
            // Got an ID token from Google. Use it to authenticate
            // with Firebase.
            val firebaseCredential = GoogleAuthProvider.getCredential(idToken, null)
            auth.signInWithCredential(firebaseCredential)
                    .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)
                        }
                    }
        }
        else -> {
            // Shouldn't happen.
            Log.d(TAG, "No ID token!")
        }
    }
    

    Java

    SignInCredential googleCredential = oneTapClient.getSignInCredentialFromIntent(data);
    String idToken = googleCredential.getGoogleIdToken();
    if (idToken !=  null) {
        // Got an ID token from Google. Use it to authenticate
        // with Firebase.
        AuthCredential firebaseCredential = GoogleAuthProvider.getCredential(idToken, null);
        mAuth.signInWithCredential(firebaseCredential)
                .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 = 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 funkcji signInWithCredential powiedzie się, możesz użyć metody getCurrentUser , aby uzyskać dane konta użytkownika.

Następne kroki

Gdy użytkownik zaloguje się po raz pierwszy, tworzone jest nowe konto użytkownika, które jest łączone z poświadczeniami — czyli nazwą użytkownika i hasłem, numerem telefonu lub informacjami o dostawcy uwierzytelniania — za pomocą których użytkownik się logował. To nowe konto jest przechowywane jako część Twojego projektu Firebase i może służyć do identyfikacji użytkownika w każdej aplikacji w Twoim projekcie, niezależnie od tego, jak użytkownik się loguje.

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

  • W regułach bezpieczeństwa Firebase Realtime Database i Cloud Storage możesz uzyskać 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ę do Twojej aplikacji przy użyciu wielu dostawców uwierzytelniania, łącząc poświadczenia dostawcy uwierzytelniania z istniejącym kontem użytkownika.

Aby wylogować użytkownika, wywołaj signOut :

Kotlin+KTX

Firebase.auth.signOut()

Java

FirebaseAuth.getInstance().signOut();