Implement Face ID Biometric Login in Flutter: A Complete, Secure Guide
Implement secure, polished Face ID (biometric) login in Flutter with local_auth, secure storage, platform setup, UX patterns, testing, and best practices.
Image used for representation purposes only.
Why add Face ID to your Flutter app?
Biometric login is the fastest way to turn a secure session into a delightful one. On iOS, Face ID provides strong, hardware‑backed authentication with an excellent user experience. In Flutter, you can enable Face ID (and other biometrics) with a small amount of code—while preserving platform security guarantees—by leaning on Apple’s LocalAuthentication framework and Android’s BiometricPrompt via Flutter plugins.
This guide walks you through a production‑ready setup, covering platform configuration, implementation, UX patterns, testing, and security pitfalls.
How Flutter biometric auth works
Flutter doesn’t talk to Face ID directly. Instead, you call a plugin that bridges to the native APIs:
- iOS: LocalAuthentication (Face ID / Touch ID or device passcode)
- Android: BiometricPrompt (strong biometrics such as fingerprint or face, plus optional device credential)
In most apps you’ll:
- Check whether biometrics are supported and enrolled.
- Prompt the user with a platform sheet (Face ID on iOS).
- If authentication succeeds, unlock a session token stored securely on‑device.
Approaches to “biometric login”
There are two common models. Pick one consciously.
-
Gate-only model (simplest):
- Store session/refresh tokens in secure storage.
- Use biometrics as a gate before reading/using those tokens.
- Pros: Easy to implement. Cons: Secret isn’t cryptographically bound to biometrics.
-
Biometric-bound secret (stronger):
- Encrypt the secret with a key that requires biometric user presence to decrypt.
- Pros: Even if app data leaks, the secret is unreadable without a successful biometric.
- Cons: Slightly more work; behavior varies by platform.
This tutorial implements the gate-only model with local_auth and flutter_secure_storage, then explains how to level up.
Prerequisites
- Flutter 3.x or newer
- iOS 13+ target recommended (Face ID requires iPhone with Face ID)
- Android 6.0 (API 23)+ if you plan to support Android biometrics alongside iOS
Project setup
Add dependencies to pubspec.yaml:
dependencies:
flutter:
sdk: flutter
local_auth: ^2.0.0
flutter_secure_storage: ^9.0.0
Android minimum SDK (required for biometrics):
// android/app/build.gradle
android {
defaultConfig {
minSdkVersion 23
}
}
iOS configuration for Face ID
Add the usage description so iOS can show a clear reason for Face ID access:
<!-- ios/Runner/Info.plist -->
<key>NSFaceIDUsageDescription</key>
<string>We use Face ID to quickly and securely sign you in.</string>
That’s all you generally need. No extra entitlements are required just for Face ID prompts.
Tip: If you allow fallback to device passcode (recommended), iOS will still show the Face ID sheet first and let users switch to passcode.
Android notes (if supporting both platforms)
- Ensure minSdkVersion is 23 or higher.
- The plugin delegates to BiometricPrompt. On emulators you’ll mostly test with fingerprint; real Android devices may also support face authentication, but the UX and availability vary by OEM.
Implementing Face ID with local_auth
Create a small authentication utility. It checks support, displays the prompt, and returns a boolean.
import 'package:local_auth/local_auth.dart';
import 'package:flutter/services.dart';
class BiometricAuth {
final LocalAuthentication _auth = LocalAuthentication();
Future<bool> isSupported() async {
final deviceSupported = await _auth.isDeviceSupported();
final canCheck = await _auth.canCheckBiometrics;
return deviceSupported && canCheck;
}
Future<List<BiometricType>> available() => _auth.getAvailableBiometrics();
Future<bool> authenticate({bool biometricsOnly = true}) async {
try {
// Show a platform-native sheet (Face ID on iOS)
final didAuth = await _auth.authenticate(
localizedReason: 'Authenticate to continue',
options: AuthenticationOptions(
biometricOnly: biometricsOnly, // set to false to allow device passcode fallback
stickyAuth: false, // set true if you need auth to persist across app pauses
useErrorDialogs: true,
sensitiveTransaction: true,
),
);
return didAuth;
} on PlatformException catch (e) {
// Handle notable cases explicitly in your UI
switch (e.code) {
case auth_error.notAvailable:
case auth_error.notEnrolled:
case auth_error.lockedOut:
case auth_error.permanentlyLockedOut:
case auth_error.passcodeNotSet:
// Decide how to inform the user / fall back to password
return false;
default:
return false;
}
}
}
}
Use it from your login screen:
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({Key? key}) : super(key: key);
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final _bio = BiometricAuth();
final _storage = const FlutterSecureStorage();
bool _faceIdAvailable = false;
@override
void initState() {
super.initState();
_init();
}
Future<void> _init() async {
final supported = await _bio.isSupported();
final types = await _bio.available();
setState(() {
_faceIdAvailable = supported && types.contains(BiometricType.face);
});
}
Future<void> _onFaceIdLogin() async {
final ok = await _bio.authenticate(biometricsOnly: true);
if (!ok) return;
// Example: read your stored refresh token and start a session
final token = await _storage.read(key: 'refresh_token');
if (token != null) {
// Exchange for access token, navigate to home, etc.
if (!mounted) return;
Navigator.of(context).pushReplacementNamed('/home');
} else {
// First-time users won’t have a token yet — fall back to password login
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Please sign in once with email/password.')),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sign in')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ElevatedButton.icon(
onPressed: _faceIdAvailable ? _onFaceIdLogin : null,
icon: const Icon(Icons.face_rounded),
label: const Text('Sign in with Face ID'),
),
const SizedBox(height: 12),
TextButton(
onPressed: () => Navigator.pushNamed(context, '/password-login'),
child: const Text('Use password instead'),
),
],
),
),
);
}
}
Notes:
- localizedReason should explain why you’re asking for Face ID.
- biometricOnly: true disables passcode fallback. Consider setting it to false if you want passcode as a secure fallback on iOS.
- stickyAuth: true is useful if your flow may momentarily background the app (e.g., launching a browser tab) during auth.
Securely storing the session token
Use flutter_secure_storage to keep tokens in Keychain (iOS) and EncryptedSharedPreferences/Android Keystore (Android):
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class SessionStorage {
static const _storage = FlutterSecureStorage();
static const _kRefresh = 'refresh_token';
static Future<void> saveRefreshToken(String token) =>
_storage.write(key: _kRefresh, value: token);
static Future<String?> readRefreshToken() =>
_storage.read(key: _kRefresh);
static Future<void> clear() => _storage.deleteAll();
}
Best practices:
- Store refresh tokens, not raw passwords.
- Rotate/renew tokens server‑side on a schedule.
- Clear tokens on explicit logout and on certain risk signals (e.g., too many failed biometric attempts).
Level up: Bind secrets to biometrics
If you want the secret to be unreadable without a successful biometric each time, use a storage plugin that enforces biometric unlock at the cryptographic layer (for example, packages that wrap iOS Keychain with kSecAccessControlBiometryCurrentSet and Android Keystore keys gated by BiometricPrompt).
Characteristics of this approach:
- The OS enforces “user presence” to decrypt.
- If biometrics are removed/re‑enrolled, the protected item becomes inaccessible, forcing re‑login.
Use this when regulatory or organizational policy requires biometric‑bound keys.
UX patterns that feel native
- Offer opt‑in after first password login: “Use Face ID next time?”
- Provide a clear fallback: “Use passcode/password instead.” Never trap users behind biometrics.
- Respect frequency: Avoid prompting at every app open; gate only sensitive actions or after a short inactivity window.
- Copy platform language: On iOS, say “Face ID”; on Android, say “Biometric” or “Fingerprint/Face” based on availability.
Handling errors and edge cases
Expect and design for these outcomes:
- Not available: Device lacks biometrics.
- Not enrolled: User hasn’t set up Face ID.
- Locked out: Too many failed attempts; OS may require passcode.
- Permanently locked (Android): Requires re‑enrolling biometrics.
- Passcode not set (iOS) when allowing device credential fallback.
Map them to friendly guidance: “Set up Face ID in Settings to enable quick sign‑in.”
Testing Face ID during development
- iOS Simulator:
- Hardware > Face ID > Enrolled (or Features > Face ID > Enrolled depending on Xcode version).
- Trigger a prompt from your app, then choose Matching Face / Non‑matching Face from the same menu.
- Real devices:
- Always test on at least one physical iPhone with Face ID to verify timing and UI.
- Android Emulator:
- Test the same code path with fingerprint; use Extended Controls > Fingerprint to simulate matches.
Security checklist
- Don’t store raw passwords on-device—use tokens.
- Use HTTPS/TLS pinning only if you understand update and recovery implications.
- Clear sensitive data on logout and when the OS signals biometric changes.
- Throttle retries and show minimal error detail on auth failures.
- Log authentication events carefully; never log secrets or biometric outcomes.
- Consider jailbreak/root detection if your threat model requires it, but design graceful fallbacks.
Fallback and recovery flows
- First run: Require a full credential login and then let users enable Face ID.
- Disabled/changed biometrics: Detect failure, wipe biometric‑bound keys if used, and send users to password login.
- Parental controls or MDM restrictions: Treat as “not available” and fall back.
Frequently asked questions
- Is Face ID a replacement for passwords? Often no. It’s best as a second factor or a convenient unlock for an existing session/token system.
- Can I force Face ID every time? You can, but balance security with UX. Many apps only require it for high‑risk actions (payments, viewing PII) or after an inactivity timeout.
- What about passkeys (WebAuthn)? Passkeys are public‑key credentials synced across devices and can use Face ID to unlock. If your server supports passkeys, consider a separate passkey flow for passwordless sign‑in; it complements, not replaces, local device biometrics for session unlock.
Putting it all together
With a few lines of code and the right platform settings, you can ship a Face ID experience that’s fast, secure, and familiar. Start with local_auth + flutter_secure_storage for a clean MVP, and graduate to biometric‑bound storage if your threat model calls for it. Invest in helpful fallbacks and testing, and your users will feel the polish from day one.
Related Posts
Flutter Speech Recognition (STT) Tutorial: Real‑Time Transcription on Android & iOS
Build a Flutter speech-to-text app with speech_to_text: setup, permissions, real-time UI, locales, and pro tips for accuracy, UX, and scalability.
Flutter Screenshot Capture and Sharing: From RepaintBoundary to share_plus
Capture any Flutter widget as an image and share it cross‑platform. Learn RepaintBoundary, screenshot, and share_plus with production tips.
Flutter NFC: Read and Write NDEF Tags on Android and iOS
Learn to read and write NFC tags in Flutter with nfc_manager: setup, NDEF records, code, UX, capacity, and cross‑platform pitfalls.