Możesz zezwolić użytkownikom na uwierzytelnianie w Firebase przy użyciu ich kont Google.
Zanim zaczniesz
Jeśli jeszcze tego nie zrobiłeś, dodaj Firebase do swojego 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ść dla uwierzytelniania Firebase Biblioteka Androida. 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:32.3.1")) // 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.7.0") }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:22.1.2")
// Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:20.7.0") }Java
dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:32.3.1")) // 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.7.0") }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:22.1.2")
// Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:20.7.0") }Jeśli jeszcze nie określiłeś odcisku cyfrowego SHA 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 aplikacji.
- Włącz Google jako metodę logowania w konsoli Firebase:
- W konsoli Firebase otwórz sekcję Auth .
- Na karcie Metoda logowania włącz metodę logowania Google i kliknij Zapisz .
Po wyświetleniu monitu w konsoli pobierz zaktualizowany plik konfiguracyjny Firebase (
google-services.json
), który zawiera teraz informacje o kliencie OAuth wymagane do logowania się przez Google.Przenieś ten zaktualizowany plik konfiguracyjny do swojego projektu Android Studio, zastępując nieaktualny odpowiedni plik konfiguracyjny. (Zobacz Dodawanie Firebase do projektu na Androida .)
Uwierzytelnij w Firebase
- 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 metodęsetGoogleIdTokenRequestOptions
:Musisz przekazać identyfikator klienta „serwera” do metodyKotlin+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();
setGoogleIdTokenRequestOptions
. Aby znaleźć identyfikator klienta OAuth 2.0:- Otwórz stronę Poświadczenia w konsoli GCP.
- Identyfikator klienta typu aplikacji internetowej to identyfikator klienta OAuth 2.0 serwera zaplecza.
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; } } }
- W metodzie
onCreate
aktywności związanej z logowaniem pobierz udostępnioną instancję obiektuFirebaseAuth
:Kotlin+KTX
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
Java
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
- 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); }
- W programie 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:Jeśli wywołanie funkcjiKotlin+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); } } }); }
signInWithCredential
powiedzie się, możesz użyć metodygetCurrentUser
, 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();