אתם יכולים לאפשר למשתמשים שלכם לבצע אימות ב-Firebase באמצעות חשבונות Google שלהם.
לפני שמתחילים
אם עדיין לא עשיתם זאת, אתם צריכים להוסיף את Firebase לפרויקט Android.
בקובץ Gradle של המודול (ברמת האפליקציה) (בדרך כלל
<project>/<app-module>/build.gradle.ktsאו<project>/<app-module>/build.gradle), מוסיפים את התלות בספריית Firebase Authentication ל-Android. מומלץ להשתמש ב-Firebase Android BoM כדי לשלוט בניהול הגרסאות של הספריות.בנוסף, במסגרת ההגדרה של Firebase Authentication, צריך להוסיף את Credential Manager SDK לאפליקציה.
dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.9.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:24.0.1")
// 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") }אם עדיין לא ציינתם את טביעת האצבע של ה-SHA של האפליקציה, אתם צריכים לעשות את זה דרך דף ההגדרות במסוף Firebase. לקבלת פרטים על קבלת טביעת האצבע של ה-SHA של האפליקציה, אפשר לעיין במאמר בנושא אימות הלקוח.
- מפעילים את Google כשיטת כניסה במסוף Firebase:
- במסוף Firebase, פותחים את הקטע אימות.
- בכרטיסייה שיטת כניסה, מפעילים את שיטת הכניסה Google ולוחצים על שמירה.
כשמוצגת בקשה במסוף, מורידים את קובץ התצורה המעודכן של Firebase (
google-services.json), שכולל עכשיו את פרטי לקוח OAuth שנדרשים לכניסה באמצעות חשבון Google.מעבירים את קובץ התצורה המעודכן הזה לפרויקט ב-Android Studio, ומחליפים את קובץ התצורה התואם שכבר לא עדכני. (ראו איך מוסיפים את Firebase לפרויקט Android).
אימות באמצעות Firebase
- כדי לשלב את 'כניסה באמצעות חשבון Google' באפליקציה, פועלים לפי השלבים שמפורטים במסמכי התיעוד של Credential Manager. הנה הוראות כלליות:
- יוצרים מופע של בקשת כניסה באמצעות חשבון 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();
בבקשה שלמעלה, צריך להעביר את מזהה הלקוח של השרת לשיטה
setServerClientId. כדי למצוא את מזהה הלקוח ב-OAuth 2.0:- פותחים את הדף Credentials במסוף Google Cloud.
- מזהה הלקוח מסוג אפליקציית אינטרנט הוא מזהה הלקוח של OAuth 2.0 של שרת הקצה העורפי.
- אחרי שמשלבים את 'כניסה באמצעות חשבון 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!"); } }
- יוצרים מופע של בקשת כניסה באמצעות חשבון Google באמצעות
- ב-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();
- כשמאתחלים את הפעילות, בודקים אם המשתמש מחובר כרגע:
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); }
- עכשיו מקבלים את אסימון הזהות של 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מצליחה, אפשר להשתמש בשיטהgetCurrentUserכדי לקבל את נתוני החשבון של המשתמש.
השלבים הבאים
אחרי שהמשתמש מתחבר בפעם הראשונה, נוצר חשבון משתמש חדש שמקושר לפרטי הכניסה – כלומר, שם המשתמש והסיסמה, מספר הטלפון או פרטי ספק האימות – שבאמצעותם המשתמש התחבר. החשבון החדש הזה נשמר כחלק מפרויקט Firebase, ואפשר להשתמש בו כדי לזהות משתמש בכל האפליקציות בפרויקט, בלי קשר לשיטת הכניסה של המשתמש.
באפליקציות, אפשר לקבל את פרטי הפרופיל הבסיסיים של המשתמש מאובייקט
FirebaseUser. איך מנהלים משתמשיםב-Firebase Realtime Database וב-Cloud Storage Security Rules, אפשר לקבל את מזהה המשתמש הייחודי של המשתמש המחובר מהמשתנה
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()); } }); }