Sub topic 6
Keeping secrets in secure storage
This chapter assumes you can already save settings with shared_preferences, write async Dart with await, and add a package to pubspec.yaml. You need those to follow the code. The goal is to store tokens and other credentials in a place the operating system protects, and to understand what that protection does and doesn't cover.
Why preferences are the wrong place for secrets
shared_preferences writes plain text. On Android the values sit in an XML file in the app's private directory. On iOS they sit in NSUserDefaults, which is a property list. The sandbox keeps other apps out. It does not protect the data in these cases:
- The device is rooted or jailbroken.
- Someone extracts an unencrypted device backup.
- The data leaks through a debugging tool.
- A bug in your own app writes the file somewhere readable.
Anything that grants access to an account is a secret. That includes access and refresh tokens, API keys the user typed in, and database encryption keys. A dark-mode flag is not a secret.
flutter_secure_storage stores values using each platform's credential store. It encrypts them, and the key is held by the operating system rather than by your app.
| Platform | Backing store |
|---|---|
| iOS and macOS | Keychain |
| Android | Values encrypted with a key held in the Android Keystore |
| Linux | libsecret (the desktop's keyring service) |
| Windows | Windows Credential API or an encrypted file, depending on package version |
| Web | Encrypted `localStorage` using WebCrypto |
The web row is the weakest. The encryption key must be reachable by the page's JavaScript, so any script injected into your page can read the values. Treat web secure storage as obfuscation, not protection.
Setting up
Add the package and run flutter pub get.
dependencies:
flutter_secure_storage: ^9.2.2Check the current version on pub.dev. Major versions have changed Android defaults and option names, so confirm the API against the version you install. On Android, check that your minSdkVersion meets the version's stated requirement. The older default storage needs API 23, and your android/app/build.gradle must allow it.
The basic API
The API is a small asynchronous key-value interface. Keys and values are both String.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
const _storage = FlutterSecureStorage();
Future<void> saveToken(String token) =>
_storage.write(key: 'auth_token', value: token);
Future<String?> readToken() => _storage.read(key: 'auth_token');
Future<void> clearToken() => _storage.delete(key: 'auth_token');Four behaviors matter here:
readreturnsnullwhen the key doesn't exist, so check for it. Anulltoken means "not signed in".- Writing
nullas the value deletes the key. Usedeletewhen you mean to delete, so the code says what it does. readAll()returns every stored pair as aMap<String, String>.deleteAll()removes everything.containsKey(key: ...)checks existence without reading the value.
Values must be strings. To store structured data, encode it first with jsonEncode, using the same toMap approach as the file storage chapter. Store the smallest thing you need. A refresh token is a good candidate. The user's whole profile is not, because it can live in an ordinary file or database.
Platform options
Each platform has its own options object. For iOS, the useful setting is when the item can be read, called accessibility.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
const _iosOptions = IOSOptions(
accessibility: KeychainAccessibility.first_unlock,
);
const _storage = FlutterSecureStorage(iOptions: _iosOptions);
Future<void> saveRefreshToken(String token) =>
_storage.write(key: 'refresh_token', value: token);The accessibility values trade safety against convenience:
unlockedmakes the item readable only while the device is unlocked. It is the strictest option that doesn't tie the item to the device.first_unlockmakes the item readable after the user unlocks the device once following a reboot. Choose this if background work, such as a push-triggered sync, needs the token while the phone is locked. Withunlocked, that work fails.- The
_this_devicevariants keep the item out of backups and device migrations.
Write the options once and share them. If you write with one set of options and read with another, the read can return null because the Keychain treats the items as different. The same applies to Android options such as a custom shared preferences name.
Wrapping the storage in a class
Calling the plugin from widgets scatters string keys through your code. Put keys and encoding in one class. The class also gives you something to replace in tests.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
abstract class TokenStore {
Future<void> save(String accessToken, String refreshToken);
Future<String?> accessToken();
Future<String?> refreshToken();
Future<void> clear();
}
class SecureTokenStore implements TokenStore {
SecureTokenStore([FlutterSecureStorage? storage])
: _storage = storage ??
const FlutterSecureStorage(
iOptions: IOSOptions(
accessibility: KeychainAccessibility.first_unlock,
),
);
static const _accessKey = 'access_token';
static const _refreshKey = 'refresh_token';
final FlutterSecureStorage _storage;
@override
Future<void> save(String accessToken, String refreshToken) async {
await _storage.write(key: _accessKey, value: accessToken);
await _storage.write(key: _refreshKey, value: refreshToken);
}
@override
Future<String?> accessToken() => _storage.read(key: _accessKey);
@override
Future<String?> refreshToken() => _storage.read(key: _refreshKey);
@override
Future<void> clear() async {
await _storage.delete(key: _accessKey);
await _storage.delete(key: _refreshKey);
}
}Delete only the keys you own in clear. deleteAll() is simpler, but it also removes anything else your app keeps in the same storage.
Edge cases and common errors
Data survives uninstall on iOS
Keychain items are not removed when the user deletes the app. A reinstall can find the previous user's token and treat them as signed in. A common fix is to store a flag in shared_preferences on first launch. Preferences are wiped on uninstall. If the flag is missing at startup, call deleteAll() on secure storage before continuing.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:shared_preferences/shared_preferences.dart';
Future<void> clearStaleSecretsOnFreshInstall() async {
final prefs = await SharedPreferences.getInstance();
if (prefs.getBool('has_launched') ?? false) return;
await const FlutterSecureStorage().deleteAll();
await prefs.setBool('has_launched', true);
}Call it in main() after WidgetsFlutterBinding.ensureInitialized() and before you read any token.
Android backup restores data it cannot decrypt
The Keystore key never leaves the device, but Android Auto Backup can restore the encrypted file to a new device. The new device has no matching key, so reads throw an exception such as a bad padding error. Two defenses work together:
- Exclude the plugin's storage file from backup with
android:allowBackup="false"or backup rules in your manifest. - Wrap reads in
try/catch. On failure, delete the stored data and send the user to sign in again.
Future<String?> safeRead(FlutterSecureStorage storage, String key) async {
try {
return await storage.read(key: key);
} catch (_) {
await storage.deleteAll();
return null;
}
}A catch-all is acceptable here. A secret you can't decrypt is useless, and the recovery path is the same whatever the cause.
Reads are asynchronous and slower than preferences
Keychain and Keystore calls cross into native code and can take noticeable time on older Android devices. Don't call them in build. Read the token once at startup, keep it in app state, and write to storage only when it changes.
Secure storage is not a vault against a compromised device
If an attacker has root access to a running device, they can ask your app's process for the decrypted value. Secure storage protects data at rest. It does not protect against malware inside your process. For real protection, use short-lived access tokens, so a stolen one expires, and let the server revoke refresh tokens.
Do not log or hard-code secrets
Never print tokens with print or debugPrint. Never bundle API keys in Dart source and assume secure storage covers them. Strings in your compiled app can be extracted. A key the user supplies can be stored securely. A key you ship in the binary is not secret.
When to use it, and when not to
Use secure storage for small, sensitive values: tokens, passwords, encryption keys. Don't use it for general data. It is slower than preferences, has no queries, and storing megabytes of data in it is a misuse. A common pattern is to keep a generated encryption key in secure storage and use that key to encrypt a larger database or file.
Exercise
A user signs out of your iOS app, then deletes and reinstalls it. On the next launch your code reads refresh_token from fluttersecurestorage and finds a value, so the app signs in automatically as the old account. What causes this, and what is one way to prevent it?
Show answer
Keychain items persist after the app is uninstalled, unlike sharedpreferences data. Prevent it by storing a "haslaunched" flag in shared_preferences on first launch. On startup, if the flag is missing, call deleteAll() on secure storage before reading any token, then set the flag. Clearing the token on sign-out also avoids the problem in this scenario, because the sign-out step should have deleted it.
Exercise
You write a token with FlutterSecureStorage(iOptions: IOSOptions(accessibility: KeychainAccessibility.unlocked)) in one file and read it with a plain FlutterSecureStorage() in another. Reads sometimes return null. Why, and how do you fix the design?
Show answer
The Keychain can treat items written with different accessibility options as different items, so the second instance does not find the value. Fix it by creating the storage instance and its options in one place, such as the SecureTokenStore class, and using only that class everywhere.