Sub topic 11
Adding a biometric check with a separate package
This chapter assumes you finished the token repository chapter. It also assumes you know async/await and can edit AndroidManifest.xml and Info.plist. You will add a fingerprint or face check in front of the stored refresh token and learn what that check does and does not protect.
What a biometric check adds
flutter_secure_storage does not ask the user to prove who they are. Any code running inside your app process can call read and get the value. A biometric check adds a second condition: the user must pass a fingerprint, face or device-credential prompt before your code reads the secret.
The usual package for this is local_auth, published by the Flutter team. It is separate from flutter_secure_storage. The two packages do not know about each other, so you connect them yourself.
This is useful for actions where you want fresh proof of presence:
- Opening the app after it was in the background for a while.
- Showing a stored card number or API key.
- Confirming a payment or a change to account security settings.
Setup
Add the package:
flutter pub add local_authAndroid
Android needs two changes. First, declare the permission in android/app/src/main/AndroidManifest.xml, inside the manifest element:
<uses-permission android:name="android.permission.USE_BIOMETRIC"/>Second, the main activity must extend FlutterFragmentActivity, because the system prompt is a fragment. In android/app/src/main/kotlin/.../MainActivity.kt:
package com.example.myapp
import io.flutter.embedding.android.FlutterFragmentActivity
class MainActivity : FlutterFragmentActivity()Keep your own package name on the first line. The activity theme must also be an AppCompat-based theme. Recent templates usually satisfy this, but check the local_auth README if the prompt crashes on launch.
iOS
Add a Face ID usage description to ios/Runner/Info.plist. Without it, iOS devices with Face ID fail the prompt:
<key>NSFaceIDUsageDescription</key>
<string>Confirm your identity to unlock your saved session.</string>Touch ID does not need this key.
Checking availability
A device may have no sensor, no enrolled fingerprint or face, or no screen lock at all. Ask before you prompt.
import 'package:local_auth/local_auth.dart';
Future<void> describeDevice() async {
final auth = LocalAuthentication();
final supported = await auth.isDeviceSupported();
final canCheck = await auth.canCheckBiometrics;
final enrolled = await auth.getAvailableBiometrics();
print('Device supports local auth: $supported');
print('Biometric hardware usable: $canCheck');
print('Enrolled types: $enrolled'); // for example [face] or [fingerprint]
}These three calls answer different questions:
| Call | What it tells you |
|---|---|
| `isDeviceSupported()` | The device can authenticate in some way, including a PIN, pattern or passcode. |
| `canCheckBiometrics` | Biometric hardware exists. It does not always mean a biometric is enrolled. |
| `getAvailableBiometrics()` | The biometric types that are enrolled, such as face or fingerprint. |
If isDeviceSupported() is true but the enrolled list is empty, the user may only have a passcode. Decide whether that is acceptable for your app.
A small gate class
Put the prompt behind your own class, as you did with storage. Screens and repositories then depend on a small interface that tests can replace.
import 'package:local_auth/local_auth.dart';
abstract class UserPresenceCheck {
Future<bool> confirm(String reason);
}
class BiometricGate implements UserPresenceCheck {
BiometricGate([LocalAuthentication? auth])
: _auth = auth ?? LocalAuthentication();
final LocalAuthentication _auth;
@override
Future<bool> confirm(String reason) async {
try {
if (!await _auth.isDeviceSupported()) {
return false;
}
return await _auth.authenticate(localizedReason: reason);
} on Exception {
// Cancelled, locked out, not enrolled, or a platform failure.
return false;
}
}
}The class fails closed: every error path returns false. A gate that returns true when something goes wrong is worse than no gate.
authenticate also accepts options, such as restricting the prompt to biometrics only or keeping it alive when the app goes to the background. Where those options live changed between major versions of local_auth: older versions use an AuthenticationOptions object, and newer ones use direct named parameters. Check the version in your pubspec.yaml against the package's API docs before you add them. Also note that version 3 reports failures with its own LocalAuthException type and older versions use PlatformException. Catching Exception covers both.
Guarding the token repository
Now combine the gate with the repository from the earlier chapter. Compose them in a thin wrapper. Do not edit TokenRepository itself, so it stays simple to test.
class GuardedTokenReader {
GuardedTokenReader({
required TokenRepository tokens,
required UserPresenceCheck presence,
this.maxAge = const Duration(minutes: 2),
DateTime Function()? clock,
}) : _tokens = tokens,
_presence = presence,
_now = clock ?? DateTime.now;
final TokenRepository _tokens;
final UserPresenceCheck _presence;
final Duration maxAge;
final DateTime Function() _now;
DateTime? _lastConfirmed;
bool get _recentlyConfirmed {
final last = _lastConfirmed;
return last != null && _now().difference(last) < maxAge;
}
/// Returns the refresh token, or null if the user did not pass the check
/// or no token is stored.
Future<String?> readRefreshToken() async {
if (!_recentlyConfirmed) {
final ok = await _presence.confirm('Unlock your saved session');
if (!ok) {
return null;
}
_lastConfirmed = _now();
}
return _tokens.readRefreshToken();
}
void lock() => _lastConfirmed = null;
}The maxAge window avoids a prompt on every read. Without it, an app that refreshes tokens several times in a minute would interrupt the user each time. Call lock() when the app moves to the background or when the user signs out.
The sequence looks like this:
Testing the guard
Because UserPresenceCheck is an interface, a fake replaces the system prompt. Combined with setMockInitialValues from the testing chapter, the whole flow runs without a device.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
class FakePresence implements UserPresenceCheck {
FakePresence(this.answer);
final bool answer;
int calls = 0;
@override
Future<bool> confirm(String reason) async {
calls++;
return answer;
}
}
void main() {
setUp(() {
FlutterSecureStorage.setMockInitialValues({'refresh_token': 'abc123'});
});
test('returns the token after a successful check', () async {
final presence = FakePresence(true);
final reader = GuardedTokenReader(
tokens: TokenRepository(),
presence: presence,
);
expect(await reader.readRefreshToken(), 'abc123');
expect(await reader.readRefreshToken(), 'abc123');
expect(presence.calls, 1); // second read is inside the window
});
test('returns null when the check fails', () async {
final reader = GuardedTokenReader(
tokens: TokenRepository(),
presence: FakePresence(false),
);
expect(await reader.readRefreshToken(), isNull);
});
}What this check does not protect
This is the most important section of the chapter. The pattern above is a user interface gate. It decides whether your Dart code makes the next call. It does not change how the token is stored.
- The token in the Keychain or Keystore-backed storage is not encrypted with a key that requires the biometric. A rooted or jailbroken device, or code injected into your process, can call
readdirectly and skip your gate. - The result of
authenticateis a boolean returned to Dart. Instrumentation tools can change a boolean. - The check proves someone passed the device's authentication. It does not prove that person is the account owner. Anyone whose fingerprint or face is enrolled on the device passes.
Stronger designs bind the secret to the authentication in the operating system. On iOS, that means Keychain access control flags that require biometry or the device passcode. On Android, it means a Keystore key that requires user authentication for each use. Newer versions of flutter_secure_storage may expose some of these options in their platform settings, and other packages target them directly. Check the current README and changelog for what your version supports. Even then, the server remains the final authority. Short-lived access tokens, refresh token rotation and server-side revocation limit the damage from a stolen token no matter what happens on the device.
Edge cases to plan for
- No biometrics enrolled. Decide on a fallback. Options are allowing the device passcode, skipping the gate, or requiring a normal sign-in. Make the choice deliberately and write it down.
- Lockout. After repeated failures the system locks biometrics for a period. Your gate returns
false, so show a message and offer another way in. - Enrollment changes. If the user adds a fingerprint, your check still passes, because it only asks whether the device accepted someone. Key-bound designs can invalidate on enrollment changes. The simple gate cannot.
- Background prompts. If the app is paused while the prompt is open, behavior differs between platforms and versions. Test it with a real device and lock the gate when the app resumes.
- Emulators. Simulators can fake enrolled biometrics, but behavior differs from real hardware. Test the final flow on a physical phone.
Exercise
A teammate adds a biometric prompt before every call to read and says tokens are now "encrypted behind the fingerprint". Is that correct? Name one change that would bind the secret to the authentication.
Show answer
No. The prompt only controls whether the app's Dart code makes the call. The stored token is not encrypted with a key that needs the fingerprint, so code on a compromised device can read it directly without the prompt. To bind the secret to authentication, use platform access control that the operating system enforces, such as iOS Keychain access control flags that require biometry or the passcode, or an Android Keystore key that requires user authentication for each use. Check which of these your version of flutter_secure_storage supports.
Exercise
In GuardedTokenReader, why does BiometricGate.confirm return false inside the on Exception block instead of rethrowing, and what is the cost of the maxAge window?
Show answer
Returning false makes the gate fail closed: any cancellation, lockout, missing enrollment or platform error means the secret is not released. The maxAge window avoids repeated prompts but weakens the guarantee, because anyone using the unlocked app during that window can read the token without a new check. Shorten the window or call lock() on backgrounding for higher-risk actions.