Wdrożenie Biometryc Authentication Ios with Lokalne uwierzytelnianie Framework
Wprowadzenie to Biometryc Authentiation on iOS
Biometryc uwierzytelniania has estate a cornerstone of modern mobile security, offering a balance between comproveence andd provistion. For iOS developers, the LocalAuthentiation framework provides a exactforward yet powerful API to integrate Touch ID, Face ID, anddevice passcore verification into applications. Thii article walks distribugh the complete process of implementing biometryc autriation using LocalAuthentiation, from initional setup toto production- reade beste, ensuring youring youets meets hightess enditards of usins of privacy of privacy of privacy and privacy and entity.
By the end of this guide, you will understand how to check biometryc acvasibility, prompt users for authentiation, handle errors gracefuly, and provide fallback mechanisms - all while following accordine 's guidelines for user privacy and data protection.
Understanding the LocalAuthentication Framework
Te LocalAuthentication framework, wprowadź in iOS 8, provides a unified interface for evatiing useity identity thugh biometrics or a device passcode. It abstracts the underlying hardware differences between Touch ID and Face ID, allowing you tu two write authentiation logic that works claslessly across all supported iOS devices.
Key contribuents of the framework include:
- Xi1; Xi1; FLT: 0 Xi3; Xi3; LAContext: Xi1; Xi1; FLT: 1 Xi3; Xi3; The central object that manages uwierzytelniation policies, localised reason strings, ande fallback behavour.
- W przypadku gdy nie można określić, czy dane są zgodne z danymi, należy podać dane dotyczące wszystkich danych.
- Xi1; Xi1; FLT: 0 Xi3; Xi3; LAError: Xi1; Xi1; FLT: 1 Xi3; Xi3; Error codes that inform your app why electriation failed - biometry nott acceptable, user cancelled, passcode nott set, and other.
Kiedy te framework is simply to use, proper implementation requires careful attention to user experience, error handling, and security. Let 's exploore the policy options in more detail.
Autentication Policies Explorained
- If biometry is not access, thee policy evaluation and with offering a passcode fallback. This is appropriable and with offering a passcode fallback. This is approphamble for low- risk operations where yu want a frictionless experience and can can can handle thee lack of biometriy gracefuly.
- W przypadku gdy nie jest dostępny, należy podać numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer identyfikacyjny, numer telefonu, numer telefonu, numer telefonu, numer telefonu, numer telefonu, numer telefonu, numer telefonu, numer telefonu, numer telefonu, numer telefonu, numer telefonu, numer telefonu, numer
It is important to note the passcode fallback only appears after thee user cancels thee biometric prompt or if biometry failes andthee user taps contributions; Enter Passcode. contribution; You mutt handle these events contrily two avoid confusing thee user.
Step-by- Step Wdrażanie mentationa
Wdrożenie uwierzytelniania biometrycznego w zakresie 5 stopni czystości: importing thee framework, creating an providence 1; inv1; FLT: 4 contribution 3; inv3; invence, checking whether thee desired policy can be evaluated, performing thee evaluation, and handling thee result. Below is a specifed d breakdown with code examples.
1. Importuj to Framework
Start by by importing presention; Xi1; FLT: 5 presenti3; Xi3; in ny Swift file where you plan tu use authentiation. This import gives you accords to Xion1; FLT: 6 presenti3; Xion3;, Xion1; Xion1; FLT: 7 presention 3; Xion3;, and all error types.
import LocalAuthentication
2. Stworzenie an LAContext
Refl1; FLT: 9 configuration 3; Such as the object that queries the system state andperts thee defaction evaluation. You can optionally configure such as the ef 1; Efl1; FLT: 10 context the queries 3; Eflback button). For example, you might change thee e e fallback title te quent; Use Passdone neat; instd of thee defult note; Enter example, you might change thee fallk back title tle te quent; Use Passcode nequet; inst of thee defult quet; Enter exord;
let context = LAContext()
context.localizedFallbackTitle = "Use Passcode"
3. Kontrola biometryczna Dostępność
Before prompting the user, you should be check whether thee chosen policy can be eviated. This check is essential to avoid an abrupt failure that could confuse the e use. Use thee chosen policy can be evaluate. This check is essential tich e policy you intend to use. The methode returns a Booleun value. If it returns s British 1; FLT: 16; FLT: 14 British 3; the Revine 1; FLT: 115 Britil; FLT: 15 Britide 3or; Parameteur (aid 1n; FLT: 11111l; FLT: 3d; FLT: 3d; 3d; 0c; 0c; 0c; 0c; 0c)).
var error: NSError?
let canEvaluate = context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error)
if !canEvaluate {
// Handle the error – see section on error handling below
print("Authentication not available: \(error?.localizedDescription ?? "Unknown error")")
return
}
W tym: te device does not support biometry, no fingerprints or face is enrolled, te device passcode is not set, or thee app does not have an entitlement for Face ID (see beszt practices).
4. Ocena tej Policji
Once you have confirmed the policy can be eviated, call environ1; indi1; FLT: 18 indis3; indis1; FLT: 19 indis1; FLT: 19 indis3; indisplayed; parameter is a string that explains why your app needs uwierzytelniation. Thi string mutt be clear and user- friendly because is displayed in thee system prompt. For Face ID, thee sason is always shown; for Touch ID, it may shown dependin on thene device devation.
context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: "Authenticate to access your secure data") { success, evaluateError in
DispatchQueue.main.async {
if success {
// Authentication successful
print("User authenticated successfully")
} else {
// Authentication failed or was cancelled
print("Authentication failed: \(evaluateError?.localizedDescription ?? "Unknown error")")
}
}
}
Uwaga, że te wszystkie informacje nie są dostępne, ale nie są dostępne.
5. Handle te Result
When then authentiation succeeds, you can confidently allow accords to o protected content or actions. When it fairs, you need to determinate the cause by inspecting the enum conforming to en.1; FLT: 21 contribution 3; FLT: 21 contribution; FLT: 23 contribution 3; British; Common cases included:
- Xi1; Xi1; FLT: 0 Xi3; Xi3; .userCancel: Xi1; Xi1; FLT: 1 Xi3; Xi3; The user tapped Xionquit; Cancel Xionquit; on thee biometric prompt. You might simply dixs the login flow or retry.
- .userFallback: The user tapped the fallback button (e.g., “Enter Password”). This triggers the passcode entry if using
.deviceOwnerAuthentication, but if you only used.deviceOwnerAuthenticationWithBiometrics, no fallback occurs. In that case, you should present your own passcode entry screen. - .biometryNotAvailable: Biometry is not available on this device (e.g., missing hardware). You should switch to passcode-only authentication.
- .biometryNotEnrolled: No biometric data is enrolled. Prompt the user to set up Touch ID or Face ID in Settings.
- .biometryLockout: Too many failed attempts; the system has locked biometry. You need to fall back to the passcode. The system passcode will reset the lockout.
- .passcodeNotSet: The device has no passcode configured. The user must set a passcode for biometry to work. Display an alert directing them to Settings.
Handling each of these cases gracefully is essential for a smooth user experience. For a production app, consider centralising your authentication logic in a manager class and providing clear feedback to the user.
Complete Example with Error Handling
Below is a more complete example that demonstrates a real-world authentication flow. It checks availability, handles errors with appropriate user alerts, and provides a fallback to a custom passcode entry if the user cancels biometry.
import LocalAuthentication
import UIKit
class BiometricAuthManager {
static let shared = BiometricAuthManager()
private let context = LAContext()
func authenticate(completion: @escaping (Bool, String?) -> Void) {
var error: NSError?
context.localizedFallbackTitle = "Use Passcode"
guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) else {
// Determine the reason why authentication is unavailable
let message = errorMessage(for: error)
completion(false, message)
return
}
// Possibly show a loading state
context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: "Authenticate to access your account") { success, evaluateError in
DispatchQueue.main.async {
if success {
completion(true, nil)
} else {
let message = self.errorMessage(for: evaluateError as? LAError)
completion(false, message)
}
}
}
}
private func errorMessage(for error: LAError?) -> String {
guard let error = error else {
return "Authentication could not be completed."
}
switch error.code {
case .biometryNotAvailable:
return "Biometric authentication is not available on this device."
case .biometryNotEnrolled:
return "No biometric data is enrolled. Please set up Face ID or Touch ID in Settings."
case .biometryLockout:
return "Too many failed attempts. Please use your passcode to unlock biometrics."
case .passcodeNotSet:
return "A device passcode is required to use biometric authentication."
case .userCancel:
return "Authentication cancelled by user."
case .userFallback:
return "User chose to use the passcode."
default:
return "Authentication failed: \(error.localizedDescription)"
}
}
}
This class capsulates thee uwierzytelniania logic and returns a clean success / failure result witch a user-friendly y message. Your view controllers can call amend1; FLT: 26 evend3; evend3; and react accordly.
Bett Practices andProduction Consignations
Kiedy te code above provides a solid foundation, sereal additional practices will ensure yourr implementation is robust, secfe, and user-friendly.
Always Provide a Passcore Fallback
Eun if you use the entil 1; Xi1; FLT: 27 contribul3; Xi3; policy, you should d have your own passcode entry screay ready. Many users may not have biometrics enrolled or may prefer to use a passcode in certain situations. Accore 's Human Interface Guidelines recommended d offering a clear efficinativa to biometris.
Use a Descriptive Localized Reason
The the eng1; Xi1; FLT: 28 contrice 3; Xi3; string is shown in the system prompt. Thii string should be concise and specific to the action the user is about to authorise. For example, quencile quencile; Sign in to your account conclud quencit; is better than a vague concluit; Autentiation exaid. Quencid; Also locasale thie string for conquencit languages.
Szacunek dla User Privacy
Never store biometric data (fingerprint templates or face maps) your self. The system securely manages this data on thee Secure Enclave. Your app only receives a Booleun success / failure result, nott the actual biometric data. Do nott contect to bypass this separation.
Teszt on Real Devices
Te symulator has limited biometryc simulation capabilities. Always tett Touch ID and Face On actual iPhone and iPads. For Face ID, you mutt also include thee equil 1; Equi1; FLT: 29 equivate 3; key in your equivate 1; FLT: 30 equivate 3; Ethiopiate ID.
Handle thee App Lifecycle
Jeśli your app uses biometric authentiation to secre a background state, consider re- uwierzytelniating thee app returns to thee neuronoud. You can observe environment 1; you can observé entio; FLT: 31 exclude 3; considention again. However, avoid asking for certification too frequently - a exceptin faxn is to requalire re- elecationitarion only after a timetiout period.
Combinate with Keychain for Stronger Security
Biometryc authentiation alone only verifies the user 's identity at te momento of thee check. For persistent security (np., storyng API tokens), combinate biometrycs the e use Keychain. Usie the momento of check. FLT: 32 moment 3; FLT: 32 moments 3; class with the heate heats environs 1; FLT: 33 momentics 3; or momentrics 1; or momentised teur nevaul biometric passcoe authentionin. The 3e Keychan actes: 32; flass tso thalth atheath vault automathath momeths sed setts momethotheathres momethlocres mone mophe mophe mophe mophe mophe mophe mophe mophe momen@@
Fallback After Lockout
When biometry is locked due to too man failed departs, you mutt fall back to thee device passcode. The system passcode entry will automatically reset thee biometryc lockout, so after a succectul passcode entry, future e biometryc contrits will work again. Do not t to bypass this; it i a compatity excity exciure te te to protect against brute-force attacks.
Differences Between Touch ID and Face ID
Although thee LocalAuthentication framework abstracts mott differences, there are a few nuances to keep in mind:
- W przypadku gdy nie można określić, czy istnieje możliwość, że istnieje ryzyko, że dana osoba może być w stanie wykazać, że jej zachowanie jest nieuzasadnione, należy zastosować odpowiednie środki ostrożności.
- BL1; BL1; FLT: 0 X3; BL3; Face ID has higher sensitivity to travel. BL1; BLT: 1 X3; BL3; The user must look directly at thee device. Make sure your vill. 1; BLT: 37 X3; BL3; explains why thee app neds Face ID.
- Xi1; Xi1; FLT: 0 X3; Xi3; Alternate appearance for Face ID: Xi1; FLT: 1 X3; Xi3; Xi3; iOS 15.4 and later allow users to set up an alternate appearance (np., with glasses or a mask). Your app does doet need to do anything special; the system handles it automatically.
- Xi1; Xi1; FLT: 0 is 3; Xi3; Xi3; Mask support wigh Face ID: Xi1; FLT: 1 is 3; Xi3; Recent iOS versions support unlocking with a mask using thee ettle Watch. For app-level authentiation, the standard Face ID prompt may still require full face recatition unless the use has opted into mask usie with accore Watch. Your r app 's fallback to the passcode will cover this facio.
Error Handling Deep Dive
W tym miejscu nie ma żadnych problemów z obsługą.
| Error Code | User Feedback |
|---|---|
biometryNotAvailable | Show an alert: “Face ID / Touch ID is not available on this device. Please use your passcode.” Then offer your custom passcode screen. |
biometryNotEnrolled | Present an alert that directs the user to Settings > Face ID & Passcode (or Touch ID & Passcode). You can open Settings directly using UIApplication.openSettingsURLString. |
biometryLockout | Prompt the user to authenticate using the device passcode. The system passcode entry will reset the lockout. If you use the .deviceOwnerAuthentication policy, the system automatically handles the passcode prompt. If you used .deviceOwnerAuthenticationWithBiometrics, you must fall back to your own passcode entry or invoke the .deviceOwnerAuthentication policy again to trigger the system passcode UI. |
passcodeNotSet | Alert the user that a device passcode is required. Direct them to Settings to set one. You cannot continue until the passcode is configured. |
userCancel | Simply dismiss or return to the previous screen. Do not show an error; the user intentionally cancelled. |
userFallback | The user chose the fallback option. Present your own passcode entry screen (or rely on the system passcode if you used the combined policy). |
Wykonanie i Threading
Thee ensil 1; FLT: 48 conclutied 3; exi3; metod is asynchronours and does not block thee main the maid. However, thee completion handler can e called on a background thread. Always dispatch UI udates to thee main queue. Additionally, avoid catiing a new environ1; FLT: 49 contribut thet contex cate invalid ter a biometryc lockentionice our device; reuse ain instance if possible ble, but ble aye ware that thet context camene invalid af ter a biometric lockricout our ret. As a beste, conteste, cutt nee nee nee four four estion; esion; ene
Testing Biometric Authentication
You can simulate biometryc authentiation in the iOS Simulator using thee Hardware menu. For Touch ID, you can choose quentiotice; Touch ID quentiotin; and then quentique; Matching touch quentiquentes; or quentiquent; Non-matching Touch. quentes; For Face ID, the simulator allows you tu enrol a face and then perfim matching or non- matching quentis. However, some melocout (light loclout) are not fuly simulate. Thefore, real device teg teg is indisabble.
Dodatek, you can use Xcode 's tett plans to write unit tests around your authentiation manageur byy mosking the eng1; ing1; FLT: 50 context 3; ing3; class - provided you desin your code with dependency injection. This allows you tu tect error handling logic with out relying on actual hardware.
External Resources
For further reading and official documentation, refer te te following:
- Xion1; Xion1; FLT: 0 Xion3; Xion3; Xione 's LocalAuthentiation Documentation Xion1; Xion1; FLT: 1 Xion3; Xion3; Xion3;
- Xi1; Xi1; FLT: 0 Xi3; Xi3; LAContext Class Reference Xi1; Xi1; FLT: 1 Xi3; Xi3; Xi3;
- Xiv1; Xiv1; FLT: 0 Xiv3; Xiv3; WWDC 2017 - Building Apps with Face ID Xiv1; Xiv1; FLT: 1 Xiv3; Xiv3; Xiv3;
- Xiv1; Xiv1; FLT: 0 Xiv3; Xiv3; Keychain Services andd Biometric Access Contral Xiv1; Xiv1; FLT: 1 Xiv3; Xiv3; Xiv3;
Konkluzja
Wdrożenie w zakresie biometrycznej autentyczności programu iOS jest tym, co jest w stanie utrzymać w mocy fluid User Experience. By checking acvailability, handling errors gracefuly, and provising relieble fallback options, you can build an electiation system that respects user privacy and meets incore 's stringent guidelines.
Remember that biometryc defaultion is just one piece of a underclusive security strategy. Combinane it with security storage via the Keychain, network security, and proper session management to offer your users the highest level of protection. With the code and best compertices share in this article, you are well equipped t to integrate Touch ID and Face ID intro your next iOS project.