אם שדרגתם ל-Firebase Authentication with Identity Platform, אתם יכולים להוסיף אימות דו-שלבי באמצעות SMS לאפליקציית Android שלכם.
אימות רב-שלבי משפר את האבטחה של האפליקציה. אמנם תוקפים לרוב חודרים לסיסמאות ולחשבונות ברשתות החברתיות, אבל קשה יותר ליירט הודעת טקסט.
לפני שמתחילים
מפעילים לפחות ספק אחד שתומך באימות רב-שלבי. כל הספקים תומכים באימות רב-שלבי, חוץ מאימות באמצעות טלפון, אימות אנונימי ו-Apple Game Center.
מוודאים שהאפליקציה מאמתת את כתובות האימייל של המשתמשים. כדי להשתמש באימות רב-שלבי צריך לאמת את כתובת האימייל. כך אפשר למנוע מגורמים זדוניים להירשם לשירות באמצעות כתובת אימייל שלא בבעלותם, ואז לנעול את הבעלים האמיתי על ידי הוספת אמצעי אימות נוסף.
רושמים את הגיבוב SHA-1 של האפליקציה במסוף Firebase (השינויים יועברו אוטומטית אל Google Cloud Firebase).
פועלים לפי השלבים בקטע אימות הלקוח כדי לקבל את גיבוב SHA-1 של האפליקציה.
פותחים את מסוף Firebase.
עוברים אל Project Settings (הגדרות הפרויקט).
בקטע האפליקציות שלך, לוחצים על סמל Android.
פועלים לפי ההוראות להוספת גיבוב SHA-1.
הפעלת אימות רב-שלבי
פותחים את הדף אימות > שיטת כניסה במסוף Firebase.
בקטע Advanced, מפעילים את האפשרות SMS Multi-factor Authentication (אימות רב-שלבי באמצעות SMS).
כדאי גם להזין את מספרי הטלפון שבהם תשתמשו לבדיקת האפליקציה. אמנם לא חובה לרשום מספרי טלפון לבדיקה, אבל מומלץ מאוד לעשות זאת כדי למנוע הגבלת קצב העברת הנתונים במהלך הפיתוח.
אם עדיין לא אישרתם את הדומיין של האפליקציה, מוסיפים אותו לרשימת ההיתרים בדף אימות > הגדרות במסוף Firebase.
אופציונלי: בדף אימות > הגדרות, מגדירים מדיניות לגבי האזורים שרוצים לאפשר או לאסור שליחת הודעות SMS אליהם. הגדרת מדיניות אזורית ל-SMS יכולה לעזור להגן על האפליקציות מפני ניצול לרעה של SMS.
בחירת תבנית שיוך
אתם יכולים לבחור אם האפליקציה שלכם דורשת אימות רב-שלבי, ואיך ומתי לרשום את המשתמשים. דוגמאות לדפוסים נפוצים:
רושמים את הגורם השני לאימות של המשתמש כחלק מההרשמה. כדאי להשתמש בשיטה הזו אם האפליקציה שלכם דורשת אימות רב-שלבי מכל המשתמשים.
הציעו אפשרות דילוג על הוספת אמצעי אימות נוסף במהלך ההרשמה. אפליקציות שרוצות לעודד אימות רב-שלבי, אבל לא לחייב אותו, עשויות להעדיף את הגישה הזו.
אפשרות להוסיף אימות דו-שלבי מדף ניהול החשבון או הפרופיל של המשתמש, במקום ממסך ההרשמה. כך מצמצמים את החיכוך במהלך תהליך ההרשמה, ועדיין מאפשרים למשתמשים שחשובה להם האבטחה להשתמש באימות רב-שלבי.
הוספה הדרגתית של אמצעי אימות נוסף כשמשתמש רוצה לגשת לתכונות עם דרישות אבטחה מוגברות.
רישום של גורם שני
כדי לרשום גורם משני חדש למשתמש:
מאמתים מחדש את המשתמש.
מבקשים מהמשתמש להזין את מספר הטלפון שלו.
קבלת סשן עם אימות רב-שלבי עבור המשתמש:
Kotlin
user.multiFactor.session.addOnCompleteListener { task -> if (task.isSuccessful) { val multiFactorSession: MultiFactorSession? = task.result } }Java
user.getMultiFactor().getSession() .addOnCompleteListener( new OnCompleteListener<MultiFactorSession>() { @Override public void onComplete(@NonNull Task<MultiFactorSession> task) { if (task.isSuccessful()) { MultiFactorSession multiFactorSession = task.getResult(); } } });יוצרים אובייקט
OnVerificationStateChangedCallbacksכדי לטפל באירועים שונים בתהליך האימות:Kotlin
val callbacks = object : OnVerificationStateChangedCallbacks() { override fun onVerificationCompleted(credential: PhoneAuthCredential) { // This callback will be invoked in two situations: // 1) Instant verification. In some cases, the phone number can be // instantly verified without needing to send or enter a verification // code. You can disable this feature by calling // PhoneAuthOptions.builder#requireSmsValidation(true) when building // the options to pass to PhoneAuthProvider#verifyPhoneNumber(). // 2) Auto-retrieval. On some devices, Google Play services can // automatically detect the incoming verification SMS and perform // verification without user action. this@MainActivity.credential = credential } override fun onVerificationFailed(e: FirebaseException) { // This callback is invoked in response to invalid requests for // verification, like an incorrect phone number. if (e is FirebaseAuthInvalidCredentialsException) { // Invalid request // ... } else if (e is FirebaseTooManyRequestsException) { // The SMS quota for the project has been exceeded // ... } // Show a message and update the UI // ... } override fun onCodeSent( verificationId: String, forceResendingToken: ForceResendingToken ) { // The SMS verification code has been sent to the provided phone number. // We now need to ask the user to enter the code and then construct a // credential by combining the code with a verification ID. // Save the verification ID and resending token for later use. this@MainActivity.verificationId = verificationId this@MainActivity.forceResendingToken = forceResendingToken // ... } }Java
OnVerificationStateChangedCallbacks callbacks = new OnVerificationStateChangedCallbacks() { @Override public void onVerificationCompleted(PhoneAuthCredential credential) { // This callback will be invoked in two situations: // 1) Instant verification. In some cases, the phone number can be // instantly verified without needing to send or enter a verification // code. You can disable this feature by calling // PhoneAuthOptions.builder#requireSmsValidation(true) when building // the options to pass to PhoneAuthProvider#verifyPhoneNumber(). // 2) Auto-retrieval. On some devices, Google Play services can // automatically detect the incoming verification SMS and perform // verification without user action. this.credential = credential; } @Override public void onVerificationFailed(FirebaseException e) { // This callback is invoked in response to invalid requests for // verification, like an incorrect phone number. if (e instanceof FirebaseAuthInvalidCredentialsException) { // Invalid request // ... } else if (e instanceof FirebaseTooManyRequestsException) { // The SMS quota for the project has been exceeded // ... } // Show a message and update the UI // ... } @Override public void onCodeSent( String verificationId, PhoneAuthProvider.ForceResendingToken token) { // The SMS verification code has been sent to the provided phone number. // We now need to ask the user to enter the code and then construct a // credential by combining the code with a verification ID. // Save the verification ID and resending token for later use. this.verificationId = verificationId; this.forceResendingToken = token; // ... } };מאתחלים אובייקט
PhoneInfoOptionsעם מספר הטלפון של המשתמש, הסשן הרב-גורמי והקריאות החוזרות:Kotlin
val phoneAuthOptions = PhoneAuthOptions.newBuilder() .setPhoneNumber(phoneNumber) .setTimeout(30L, TimeUnit.SECONDS) .setMultiFactorSession(MultiFactorSession) .setCallbacks(callbacks) .build()Java
PhoneAuthOptions phoneAuthOptions = PhoneAuthOptions.newBuilder() .setPhoneNumber(phoneNumber) .setTimeout(30L, TimeUnit.SECONDS) .setMultiFactorSession(multiFactorSession) .setCallbacks(callbacks) .build();כברירת מחדל, האימות המיידי מופעל. כדי להשבית את ההגדרה, מוסיפים שיחה ל-
requireSmsValidation(true).שליחת הודעת אימות לטלפון של המשתמש:
Kotlin
PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions)Java
PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions);מומלץ ליידע את המשתמשים מראש שהם יקבלו הודעת SMS, ושהתעריפים הרגילים חלים על כך.
אחרי שקוד ה-SMS נשלח, מבקשים מהמשתמש לאמת את הקוד:
Kotlin
// Ask user for the verification code. val credential = PhoneAuthProvider.getCredential(verificationId, verificationCode)Java
// Ask user for the verification code. PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, verificationCode);מפעילים אובייקט
MultiFactorAssertionעםPhoneAuthCredential:Kotlin
val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential)Java
MultiFactorAssertion multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential);משלימים את ההרשמה. אפשר גם לציין שם מוצג לגורם השני. האפשרות הזו שימושית למשתמשים עם כמה אמצעי אימות, כי מספר הטלפון מוסתר במהלך תהליך האימות (לדוגמה, +1******1234).
Kotlin
// Complete enrollment. This will update the underlying tokens // and trigger ID token change listener. FirebaseAuth.getInstance() .currentUser ?.multiFactor ?.enroll(multiFactorAssertion, "My personal phone number") ?.addOnCompleteListener { // ... }Java
// Complete enrollment. This will update the underlying tokens // and trigger ID token change listener. FirebaseAuth.getInstance() .getCurrentUser() .getMultiFactor() .enroll(multiFactorAssertion, "My personal phone number") .addOnCompleteListener( new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { // ... } });
בדוגמה הבאה מוצג קוד מלא להוספת אימות דו-שלבי:
Kotlin
val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential)
user.multiFactor.session
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val multiFactorSession = task.result
val phoneAuthOptions = PhoneAuthOptions.newBuilder()
.setPhoneNumber(phoneNumber)
.setTimeout(30L, TimeUnit.SECONDS)
.setMultiFactorSession(multiFactorSession)
.setCallbacks(callbacks)
.build()
// Send SMS verification code.
PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions)
}
}
// Ask user for the verification code.
val credential = PhoneAuthProvider.getCredential(verificationId, verificationCode)
val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential)
// Complete enrollment.
FirebaseAuth.getInstance()
.currentUser
?.multiFactor
?.enroll(multiFactorAssertion, "My personal phone number")
?.addOnCompleteListener {
// ...
}
Java
MultiFactorAssertion multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential);
user.getMultiFactor().getSession()
.addOnCompleteListener(
new OnCompleteListener<MultiFactorSession>() {
@Override
public void onComplete(@NonNull Task<MultiFactorSession> task) {
if (task.isSuccessful()) {
MultiFactorSession multiFactorSession = task.getResult();
PhoneAuthOptions phoneAuthOptions =
PhoneAuthOptions.newBuilder()
.setPhoneNumber(phoneNumber)
.setTimeout(30L, TimeUnit.SECONDS)
.setMultiFactorSession(multiFactorSession)
.setCallbacks(callbacks)
.build();
// Send SMS verification code.
PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions);
}
}
});
// Ask user for the verification code.
PhoneAuthCredential credential =
PhoneAuthProvider.getCredential(verificationId, verificationCode);
MultiFactorAssertion multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential);
// Complete enrollment.
FirebaseAuth.getInstance()
.getCurrentUser()
.getMultiFactor()
.enroll(multiFactorAssertion, "My personal phone number")
.addOnCompleteListener(
new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
// ...
}
});
כל הכבוד! הוספתם בהצלחה אמצעי אימות שני למשתמש.
כניסה של משתמשים באמצעות גורם אימות שני
כדי להכניס משתמש באמצעות אימות דו-שלבי ב-SMS:
מבצעים כניסה של המשתמש באמצעות הגורם הראשון, ואז מאתרים את החריגה
FirebaseAuthMultiFactorException. השגיאה הזו מכילה רכיב לפתרון בעיות, שבעזרתו אפשר לקבל את הגורמים השניוניים שהמשתמש רשם. הוא גם מכיל סשן בסיסי שמוכיח שהמשתמש עבר אימות בהצלחה באמצעות הגורם הראשון.לדוגמה, אם הגורם הראשון של המשתמש היה אימייל וסיסמה:
Kotlin
FirebaseAuth.getInstance() .signInWithEmailAndPassword(email, password) .addOnCompleteListener( OnCompleteListener { task -> if (task.isSuccessful) { // User is not enrolled with a second factor and is successfully // signed in. // ... return@OnCompleteListener } if (task.exception is FirebaseAuthMultiFactorException) { // The user is a multi-factor user. Second factor challenge is // required. val multiFactorResolver = (task.exception as FirebaseAuthMultiFactorException).resolver // ... } else { // Handle other errors, such as wrong password. } })Java
FirebaseAuth.getInstance() .signInWithEmailAndPassword(email, password) .addOnCompleteListener( new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // User is not enrolled with a second factor and is successfully // signed in. // ... return; } if (task.getException() instanceof FirebaseAuthMultiFactorException) { // The user is a multi-factor user. Second factor challenge is // required. MultiFactorResolver multiFactorResolver = task.getException().getResolver(); // ... } else { // Handle other errors such as wrong password. } } });אם הגורם הראשון של המשתמש הוא ספק מאוחד, כמו OAuth, צריך ללכוד את השגיאה אחרי הקריאה ל-
startActivityForSignInWithProvider().אם המשתמש רשום עם כמה גורמים משניים, צריך לשאול אותו באיזה גורם הוא רוצה להשתמש:
Kotlin
// Ask user which second factor to use. // You can get the list of enrolled second factors using // multiFactorResolver.hints // Check the selected factor: if (multiFactorResolver.hints[selectedIndex].factorId === PhoneMultiFactorGenerator.FACTOR_ID ) { // User selected a phone second factor. val selectedHint = multiFactorResolver.hints[selectedIndex] as PhoneMultiFactorInfo } else if (multiFactorResolver.hints[selectedIndex].factorId === TotpMultiFactorGenerator.FACTOR_ID) { // User selected a TOTP second factor. } else { // Unsupported second factor. }Java
// Ask user which second factor to use. // You can get the masked phone number using // resolver.getHints().get(selectedIndex).getPhoneNumber() // You can get the display name using // resolver.getHints().get(selectedIndex).getDisplayName() if ( resolver.getHints() .get(selectedIndex) .getFactorId() .equals( PhoneMultiFactorGenerator.FACTOR_ID ) ) { // User selected a phone second factor. MultiFactorInfo selectedHint = multiFactorResolver.getHints().get(selectedIndex); } else if ( resolver .getHints() .get(selectedIndex) .getFactorId() .equals(TotpMultiFactorGenerator.FACTOR_ID ) ) { // User selected a TOTP second factor. } else { // Unsupported second factor. }מאחלים לאובייקט
PhoneAuthOptionsבהתאם לרמז ולסשן הרב-גורמי. הערכים האלה כלולים ב-resolver שמצורף ל-FirebaseAuthMultiFactorException.Kotlin
val phoneAuthOptions = PhoneAuthOptions.newBuilder() .setMultiFactorHint(selectedHint) .setTimeout(30L, TimeUnit.SECONDS) .setMultiFactorSession(multiFactorResolver.session) .setCallbacks(callbacks) // Optionally disable instant verification. // .requireSmsValidation(true) .build()Java
PhoneAuthOptions phoneAuthOptions = PhoneAuthOptions.newBuilder() .setMultiFactorHint(selectedHint) .setTimeout(30L, TimeUnit.SECONDS) .setMultiFactorSession(multiFactorResolver.getSession()) .setCallbacks(callbacks) // Optionally disable instant verification. // .requireSmsValidation(true) .build();שליחת הודעת אימות לטלפון של המשתמש:
Kotlin
// Send SMS verification code PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions)Java
// Send SMS verification code PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions);אחרי שקוד ה-SMS נשלח, מבקשים מהמשתמש לאמת את הקוד:
Kotlin
// Ask user for the verification code. Then, pass it to getCredential: val credential = PhoneAuthProvider.getCredential(verificationId, verificationCode)Java
// Ask user for the verification code. Then, pass it to getCredential: PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, verificationCode);מפעילים אובייקט
MultiFactorAssertionעםPhoneAuthCredential:Kotlin
val multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential)Java
MultiFactorAssertion multiFactorAssertion = PhoneMultiFactorGenerator.getAssertion(credential);צריך להתקשר אל
resolver.resolveSignIn()כדי להשלים את האימות המשני. אחרי כן תוכלו לגשת לתוצאת הכניסה המקורית, שכוללת את הנתונים הספציפיים של הספק ואת פרטי האימות:Kotlin
multiFactorResolver .resolveSignIn(multiFactorAssertion) .addOnCompleteListener { task -> if (task.isSuccessful) { val authResult = task.result // AuthResult will also contain the user, additionalUserInfo, // and an optional credential (null for email/password) // associated with the first factor sign-in. // For example, if the user signed in with Google as a first // factor, authResult.getAdditionalUserInfo() will contain data // related to Google provider that the user signed in with; // authResult.getCredential() will contain the Google OAuth // credential; // authResult.getCredential().getAccessToken() will contain the // Google OAuth access token; // authResult.getCredential().getIdToken() contains the Google // OAuth ID token. } }Java
multiFactorResolver .resolveSignIn(multiFactorAssertion) .addOnCompleteListener( new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { AuthResult authResult = task.getResult(); // AuthResult will also contain the user, additionalUserInfo, // and an optional credential (null for email/password) // associated with the first factor sign-in. // For example, if the user signed in with Google as a first // factor, authResult.getAdditionalUserInfo() will contain data // related to Google provider that the user signed in with. // authResult.getCredential() will contain the Google OAuth // credential. // authResult.getCredential().getAccessToken() will contain the // Google OAuth access token. // authResult.getCredential().getIdToken() contains the Google // OAuth ID token. } } });
בדוגמה הבאה מוצג קוד מלא של כניסה של משתמש עם אימות רב-שלבי:
Kotlin
FirebaseAuth.getInstance()
.signInWithEmailAndPassword(email, password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
// User is not enrolled with a second factor and is successfully
// signed in.
// ...
return@addOnCompleteListener
}
if (task.exception is FirebaseAuthMultiFactorException) {
val multiFactorResolver =
(task.exception as FirebaseAuthMultiFactorException).resolver
// Ask user which second factor to use. Then, get
// the selected hint:
val selectedHint =
multiFactorResolver.hints[selectedIndex] as PhoneMultiFactorInfo
// Send the SMS verification code.
PhoneAuthProvider.verifyPhoneNumber(
PhoneAuthOptions.newBuilder()
.setActivity(this)
.setMultiFactorSession(multiFactorResolver.session)
.setMultiFactorHint(selectedHint)
.setCallbacks(generateCallbacks())
.setTimeout(30L, TimeUnit.SECONDS)
.build()
)
// Ask user for the SMS verification code, then use it to get
// a PhoneAuthCredential:
val credential =
PhoneAuthProvider.getCredential(verificationId, verificationCode)
// Initialize a MultiFactorAssertion object with the
// PhoneAuthCredential.
val multiFactorAssertion: MultiFactorAssertion =
PhoneMultiFactorGenerator.getAssertion(credential)
// Complete sign-in.
multiFactorResolver
.resolveSignIn(multiFactorAssertion)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
// User successfully signed in with the
// second factor phone number.
}
// ...
}
} else {
// Handle other errors such as wrong password.
}
}
Java
FirebaseAuth.getInstance()
.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(
new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// User is not enrolled with a second factor and is successfully
// signed in.
// ...
return;
}
if (task.getException() instanceof FirebaseAuthMultiFactorException) {
FirebaseAuthMultiFactorException e =
(FirebaseAuthMultiFactorException) task.getException();
MultiFactorResolver multiFactorResolver = e.getResolver();
// Ask user which second factor to use.
MultiFactorInfo selectedHint =
multiFactorResolver.getHints().get(selectedIndex);
// Send the SMS verification code.
PhoneAuthProvider.verifyPhoneNumber(
PhoneAuthOptions.newBuilder()
.setActivity(this)
.setMultiFactorSession(multiFactorResolver.getSession())
.setMultiFactorHint(selectedHint)
.setCallbacks(generateCallbacks())
.setTimeout(30L, TimeUnit.SECONDS)
.build());
// Ask user for the SMS verification code.
PhoneAuthCredential credential =
PhoneAuthProvider.getCredential(verificationId, verificationCode);
// Initialize a MultiFactorAssertion object with the
// PhoneAuthCredential.
MultiFactorAssertion multiFactorAssertion =
PhoneMultiFactorGenerator.getAssertion(credential);
// Complete sign-in.
multiFactorResolver
.resolveSignIn(multiFactorAssertion)
.addOnCompleteListener(
new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// User successfully signed in with the
// second factor phone number.
}
// ...
}
});
} else {
// Handle other errors such as wrong password.
}
}
});
כל הכבוד! התחברתם בהצלחה כמשתמש באמצעות אימות רב-שלבי.
המאמרים הבאים
- ניהול משתמשים עם אימות רב-שלבי באמצעות תוכנה עם Admin SDK.