Możesz zezwolić użytkownikom na uwierzytelnianie się w Firebase przy użyciu ich kont Google.
Zanim zaczniesz
Jeśli jeszcze tego nie zrobiono, dodaj Firebase do projektu na Androida.
W pliku Gradle modułu (na poziomie aplikacji) (zwykle
<project>/<app-module>/build.gradle.kts
lub<project>/<app-module>/build.gradle
) dodaj zależność z biblioteką 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 menedżera danych logowania.
dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:33.10.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.
(Alternatywnie) Dodaj zależności biblioteki Firebase bez BoM
Jeśli zdecydujesz się nie używać Firebase BoM, musisz określić każdą wersję biblioteki Firebase w linii zależności.
Jeśli w aplikacji używasz kilku bibliotek Firebase, zdecydowanie zalecamy korzystanie z BoM do zarządzania wersjami bibliotek. Dzięki temu wszystkie wersje będą ze sobą zgodne.
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:23.2.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") }Jeśli nie masz jeszcze określonego odcisku palca SHA aplikacji, zrób to na stronie Ustawienia konsoli Firebase. Szczegółowe informacje o tym, jak uzyskać odcisk cyfrowy SHA aplikacji, znajdziesz w artykule Uwierzytelnianie klienta.
- Włącz Google jako metodę logowania w konsoli Firebase:
- W konsoli Firebase otwórz sekcję Autoryzacja.
- Na karcie Metoda logowania włącz metodę logowania Google i kliknij Zapisz.
Gdy pojawi się taka prośba w konsoli, pobierz zaktualizowany plik konfiguracji Firebase (
google-services.json
), który zawiera informacje o kliencie OAuth wymagane do logowania się w Google.Przenieś zaktualizowany plik konfiguracji do projektu w Android Studio, zastępując nim nieaktualny plik konfiguracji. (zobacz Dodaj Firebase do projektu na Androida).
Uwierzytelnienie za pomocą Firebase
- Aby zintegrować w swojej aplikacji funkcję Logowanie z Google, wykonaj czynności opisane w dokumentacji Menedżera danych logowania. Oto ogólne instrukcje:
- Utwórz instancję żądania logowania się w Google za pomocą interfejsu
GetGoogleIdOption
. Następnie utwórz prośbę do Menedżera danych logowania 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 powyższym żądaniu musisz przekazać identyfikator klienta „server” metodzie
setServerClientId
. Aby znaleźć identyfikator klienta OAuth 2.0:- W konsoli Google Cloud otwórz stronę Dane logowania.
- Identyfikator klienta typu aplikacja internetowa to identyfikator klienta OAuth 2.0 Twojego serwera zaplecza.
- Po zintegrowaniu logowania się przez Google sprawdź, czy Twoja aktywność logowania 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!"); } }
- Utwórz instancję żądania logowania się w Google za pomocą interfejsu
- W metodzie
onCreate
aktywności logowania się pobierz udostępniony obiektFirebaseAuth
:Kotlin
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
Java
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
- 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); }
- Teraz pobierz token identyfikatora Google utworzony na potrzeby użytkownika w kroku 1, zamien 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); } }); }
signInWithCredential
się powiedzie, możesz użyć metodygetCurrentUser
, 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 dostawcy uwierzytelniania. 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 użytkownik się loguje.
W swoich aplikacjach możesz pobrać podstawowe informacje o profilu użytkownika z obiektu
FirebaseUser
. Zobacz Zarządzanie użytkownikami.W regułach Firebase Realtime Database i Cloud Storage Regułach bezpieczeństwa możesz pobrać z zmiennej
auth
unikalny identyfikator zalogowanego użytkownika i użyć go do kontrolowania dostępu użytkownika do danych.
Możesz zezwolić użytkownikom na logowanie się w aplikacji za pomocą danych logowania od wielu dostawców uwierzytelniania, połączając je z dotychczasowym kontem użytkownika.
Aby wylogować użytkownika, zadzwoń pod numer
signOut
. Musisz też wyczyścić stan danych uwierzytelniających bieżącego użytkownika we wszystkich dostawcach danych uwierzytelniających zgodnie z zaleceniami podanymi w dokumentacji menedżera danych uwierzytelniających:
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()); } }); }