Sub topic 13
Limits of on-device secure storage
This chapter assumes you have finished the earlier chapters. You should know how flutter_secure_storage writes and reads values, how the token repository is built, and how reinstalls and backups affect stored data. Here you will learn what the package does not protect against, so you can design around those gaps instead of discovering them in a security review.
What "secure" means here
flutter_secure_storage protects data at rest. On iOS the Keychain encrypts items, and on Android a key held in the Android Keystore encrypts the stored values. If someone copies the app's files off a locked device, or reads them from an unencrypted backup, they get ciphertext.
That is a narrow guarantee. The package does not protect data while your app is running, it does not protect against an attacker who controls the device, and it does not make a leaked token harmless. The sections below cover each gap.
Gap 1: a compromised device
On a rooted Android device or a jailbroken iPhone, the operating system's isolation rules no longer hold. An attacker with root access can often do the following:
- Attach a debugger or a hooking tool such as Frida to your process.
- Call
FlutterSecureStorage.readfrom inside your app, or hook the platform channel and capture the plaintext return value. - Ask the Keystore or Keychain to decrypt, because the request comes from your app's own process and identity.
Encryption does not help here. The decryption key is usable by your app, so anyone who can act as your app can use it.
Hardware backing reduces some of this risk but does not remove it. On many Android devices the Keystore keeps key material in a trusted execution environment or a dedicated security chip, so the key cannot be exported. An attacker running code as your app can still ask that hardware to decrypt. Whether a given device has such hardware, and whether the package requests it, depends on the device and the package version.
Gap 2: data in memory
After read returns, the secret is a Dart String in your app's heap. Dart strings are immutable, so you cannot overwrite them, and you cannot control when the garbage collector releases them. A memory dump of a running process on a compromised device can contain the token.
You can shrink this window with a few habits:
- Read a secret only when you need it.
- Do not store it in long-lived global variables.
- Do not log it. Logs persist and are often collected by crash reporters.
You cannot eliminate in-memory exposure, so design for the case where a token leaks.
Gap 3: secrets shipped inside the app
Secure storage holds values that your app receives or generates at runtime, such as a refresh token returned after sign-in. It cannot protect a value you compile into the app.
An API key written in Dart source, an asset file, or --dart-define ends up in the app binary. Anyone can download the app, unpack it, and search for strings. Obfuscation raises the effort slightly and stops no determined attacker. If you copy a bundled key into secure storage at first launch, the key is still extractable from the binary.
The real fix is to keep the secret on a server. Your app calls your backend, and the backend calls the third-party service with the real key. If a client key is unavoidable, restrict it on the provider's side by app identifier, by quota, and by allowed endpoints, and assume it is public.
Gap 4: the secret stays valid after it leaks
Storage can only reduce the chance of a leak. It cannot make a stolen token stop working. Limit the damage on the server side:
- Use short-lived access tokens, for example minutes rather than weeks.
- Rotate refresh tokens on every use, and detect reuse of an old one as a sign of theft.
- Support revocation, so signing out on one device, or changing a password, invalidates tokens server-side.
- Bind tokens to a device or session where your backend supports it.
The following sketch keeps the short-lived access token in memory and persists only the refresh token. The refreshCall function is a placeholder for your own network call, and it must return the new rotated refresh token.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
typedef TokenPair = ({String access, String refresh});
typedef RefreshCall = Future<TokenPair> Function(String refreshToken);
class AuthSession {
AuthSession({
required this.refreshCall,
FlutterSecureStorage? storage,
}) : _storage = storage ?? const FlutterSecureStorage();
static const _refreshKey = 'refresh_token';
final RefreshCall refreshCall;
final FlutterSecureStorage _storage;
String? _accessToken;
String? get accessToken => _accessToken;
/// Returns true if a stored refresh token produced a fresh session.
Future<bool> restore() async {
final stored = await _storage.read(key: _refreshKey);
if (stored == null) return false;
final tokens = await refreshCall(stored);
_accessToken = tokens.access;
// Rotation: the old refresh token is now useless, so replace it.
await _storage.write(key: _refreshKey, value: tokens.refresh);
return true;
}
Future<void> signOut() async {
_accessToken = null;
await _storage.delete(key: _refreshKey);
}
}If an attacker copies the refresh token, the next legitimate restore call exposes the problem. One of the two parties presents a token the server has already retired, and the server can revoke the whole chain.
Gap 5: platform behavior you do not control
Several behaviors depend on the operating system and package version, not on your code.
| Behavior | Platform | Consequence |
|---|---|---|
| Keychain items can survive app deletion | iOS | A reinstalled app may find an old token and appear signed in. |
| Android data is removed on uninstall, but backed-up files may be restored without the Keystore key | Android | Reads can throw and the data is unrecoverable. |
| Accessibility setting decides when items are readable | iOS | `first_unlock` allows background reads after the first unlock, but is weaker than `unlocked`. |
| Android implementation details change between package versions | Android | An upgrade can require a data migration. Read the changelog first. |
| Keystore keys can be invalidated by lock-screen changes on some configurations | Android | Stored values can become unreadable. |
Two practical rules follow. First, treat every read as something that can fail or return nothing, and send the user to sign in again instead of crashing. Second, treat sign-out as a server operation plus a local delete, not a local delete alone.
Gap 6: wrong tool for the job
Secure storage is built for a few small strings. It is a poor fit for:
- Large data. Each call crosses a platform channel and goes through encryption. Storing images, documents, or a large JSON cache will be slow.
- Frequently read values. Settings such as theme or language belong in
shared_preferences, which is faster and keeps your Keychain use small. - Querying. There is no search, only key lookups, and
readAllreturns everything. - Large secure databases. For these, use an encrypted database such as SQLCipher. You can generate the database key, store that one key in secure storage, and let the database handle the bulk data.
Gap 7: web and desktop
On the web, there is no hardware-backed key store available to the package. The browser implementation encrypts values with the Web Crypto API and stores them in localStorage, and the encryption key lives in the same origin. Any script that runs on your page, including one injected through cross-site scripting (XSS), can reach both. Treat web storage as obfuscation against casual inspection, not as secure storage. For web apps, prefer HttpOnly cookies set by your server, which page scripts cannot read.
Desktop platforms use the operating system's credential facilities, such as the macOS Keychain, Windows Credential Manager, or libsecret on Linux. Their guarantees vary, and any process running as the same user may be able to read them. Check the package README for the current requirements on each platform.
Where each layer helps
The diagram shows how the layers fit together, and which attacker each one stops.
Choosing alternatives
Use the table below to decide what to reach for when secure storage is not enough.
| Need | Better option |
|---|---|
| Keep a third-party API key secret | Backend proxy that holds the key |
| Require the user's presence before reading a token | Biometric check from a separate package, as covered earlier in this tutorial |
| Store large sensitive data | Encrypted database with its key in secure storage |
| Reduce damage from a stolen token | Short expiry, refresh rotation, server-side revocation |
| Authenticate a web app | Server-set `HttpOnly` cookie |
| Store non-sensitive preferences | `shared_preferences` |
A practical checklist
Before you ship, confirm each of these:
- Only runtime-issued secrets are in secure storage. No bundled keys are treated as secret.
- Access tokens are short-lived and kept in memory. Only the refresh token is persisted.
- The server rotates refresh tokens and can revoke them.
- Reads handle
nullandPlatformExceptionby returning the user to sign-in. - Sign-out calls your backend and deletes local values.
- No secret appears in logs, analytics events, or crash reports.
- The web build does not rely on the package for confidentiality.
- You have read the package README and changelog for the version you ship.
Exercise
A teammate stores a payment provider's secret API key in flutter_secure_storage at first launch, copying it from a constant in the Dart source. They say the key is now safe. What is wrong with this design, and what should you do instead?
Show answer
The key is compiled into the app binary, so anyone can extract it by unpacking the app, and copying it into secure storage afterward does not remove it from the binary. Secure storage protects values at rest on the device, not values shipped with the app. Move the key to your backend, and have the app call the backend, which then calls the payment provider. If the provider requires a client-side key, use a restricted publishable key and limit it by app identifier and permissions.
Exercise
You store a long-lived access token (valid for 90 days) in secure storage on Android and iOS. Name two ways an attacker could still use it, and two server-side changes that reduce the damage.
Show answer
An attacker could run code on a rooted or jailbroken device and call the app's own read path, or capture the token from process memory or a hooked platform channel while the app is running. Server-side, issue short-lived access tokens (for example minutes) with a refresh token, and rotate the refresh token on each use. Also support revocation on sign-out or password change, so a stolen token stops working.