Sub topic 2
What belongs in secure storage (and what does not)
This chapter assumes you know basic Dart and async/await, can add packages with pub, and understand what an authentication token is. You don't need to have installed flutter_secure_storage yet. The goal here is a decision rule: before you write a value to secure storage, you should be able to say why it belongs there.
Why the choice matters
Secure storage is a small, slow, platform-backed vault. It protects a few values very well. It does not suit large or frequently read data, and it cannot protect a secret that you ship inside your own app. Putting everything in it is a common mistake. It makes the app slower and harder to debug, and it gives a false sense that the whole app is safe.
The package keeps string values under string keys. Each call goes through a platform channel to native code, which then talks to the Keychain on iOS or to Keystore-backed storage on Android. Later chapters cover the backends in detail. For this chapter, you only need to know that the storage is designed for small secrets.
The core test
A value belongs in secure storage when all three of these are true:
- It is a secret. Someone who copied it could act as the user or read the user's protected data.
- It is small. It is a token, a key, or a short credential, not a document or a list of records.
- The app must remember it across launches. If it only needs to live while the app runs, memory is safer.
If any answer is no, look for a better place.
What belongs
Refresh tokens
A refresh token lets the app get new access tokens without asking the user to sign in again. It lives for weeks or months, and anyone holding it can keep a session going. It is the standard example for this package. The examples in this tutorial store it under the key refresh_token.
Long-lived session credentials
If your backend issues a long-lived session token or a device token instead of the OAuth refresh-token pair, the same reasoning applies. The token is secret and small, and it must survive restarts.
Per-user API keys
Some apps let users paste their own API key for a third-party service. That key belongs to the user and was created at runtime, so secure storage is a good place for it.
Encryption keys for larger data
Secure storage is not meant for large data. If you have a local database or a cache of sensitive records, encrypt that data with a key and store only the key in secure storage. The database holds the bulk, and the vault holds the 32 bytes that unlock it.
The following function creates a random key on first use and returns the same key afterwards. Values are strings, so the bytes are encoded as base64 text.
import 'dart:convert';
import 'dart:math';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
Future<List<int>> loadOrCreateDatabaseKey(FlutterSecureStorage storage) async {
const keyName = 'local_db_key';
final existing = await storage.read(key: keyName);
if (existing != null) {
return base64Url.decode(existing);
}
final random = Random.secure();
final bytes = List<int>.generate(32, (_) => random.nextInt(256));
await storage.write(key: keyName, value: base64Url.encode(bytes));
return bytes;
}Use Random.secure() for keys. The default Random() is not designed to be unpredictable.
What does not belong
Ordinary preferences
Theme choice, language, onboarding flags, and last-opened tab are not secrets. Use shared_preferences. Reading them from secure storage costs more, and if a restored backup or a platform error makes the vault unreadable, the user loses settings they should never have lost.
Short-lived access tokens
An access token often expires in minutes. Keep it in a field in memory and refresh it from the stored refresh token when the app starts. This reduces how much sensitive data sits on disk. The cost is one network call at startup, which most apps already make.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class Session {
Session(this._storage);
static const _refreshKey = 'refresh_token';
final FlutterSecureStorage _storage;
String? _accessToken; // memory only
String? get accessToken => _accessToken;
Future<void> signIn({
required String accessToken,
required String refreshToken,
}) async {
_accessToken = accessToken;
await _storage.write(key: _refreshKey, value: refreshToken);
}
Future<void> signOut() async {
_accessToken = null;
await _storage.delete(key: _refreshKey);
}
}Some teams do persist access tokens so that a cold start can skip the refresh call. That is a trade-off, not an error. If you do it, treat the access token like any other secret and clear it on sign-out.
Large or structured data
Do not store a user profile as a JSON string, a list of messages, or cached API responses. Secure storage has no query support, so you would read and decode the whole value to change one field. Every read crosses the platform channel. The platform stores are not built for large payloads. Use a database, and encrypt it if the content is sensitive.
Binary data without encoding
The API accepts strings only. If you need to store bytes, encode them first, as the key example above does with base64. If you find yourself encoding a large blob, that is a sign it belongs in an encrypted file or database.
Secrets that ship inside the app
This is the most common misunderstanding. Suppose your app contains a third-party API key, a client secret, or a signing key. The app binary has to carry that value, and anyone can unpack the binary and find it. Writing the value into secure storage at first launch does not help. The value had to be in the code, and the attacker reads it from there.
Passwords
Avoid storing the user's password. After sign-in, the server should give you a token, and the token is what you keep. A stored password is more valuable to an attacker than a token, since it often works on other sites, and it cannot be revoked with a server-side session invalidation. If you must support automatic sign-in, store a revocable token.
Data you need to share or sync
Secure storage values are local to the device and to your app. Don't use it to pass data to a widget extension or another app and expect it to work by default. Sharing needs platform-specific configuration, which this tutorial does not cover. If another app or extension needs to read a value, plan for that separately.
Quick reference
| Value | Where it goes | Reason |
|---|---|---|
| Refresh token | Secure storage | Secret, small, must persist |
| Access token (short-lived) | Memory, or secure storage if you accept the trade-off | Expires quickly, cheap to renew |
| Per-user API key | Secure storage | Secret, created at runtime |
| Database encryption key | Secure storage | Small key that protects bulk data |
| Encrypted database or file | Database or file storage | Too large for the vault |
| Theme, locale, flags | `shared_preferences` | Not secret |
| Cached API responses | Database or file cache | Large, needs queries |
| Embedded API key or client secret | Your server | The app binary cannot hide it |
| User password | Do not store | Use a revocable token |
Naming and organising keys
Because every secret is a string under a string key, typos silently create new entries. Two habits help:
- Define each key as a
constin one place. The repository in a later chapter does this. - Use clear, stable names such as
refresh_tokenorlocal_db_key. If you later change a name, the old entry stays on the device until you delete it.
Also decide up front what happens when the user signs out. Every secret you store needs a matching delete path. A short list of the keys your app writes, kept next to the code that writes them, makes that easy to check.
Common mistakes
- Treating the vault as a general database. Symptom: slow startup because the app reads many keys before the first frame. Fix: read only what you need, and move the rest elsewhere.
- Storing values you could derive. If the server can re-issue a value from the refresh token, don't also persist it.
- Assuming a stored value is safe on a compromised device. On a rooted or jailbroken device, or with an attacker who has the unlocked phone, the protection weakens. Chapter 13 covers this limit.
- Logging secrets while debugging. Printing a token to the console puts it in a place that has none of the vault's protection. Remove those prints before you ship.
- Forgetting that "I stored it" is not "I need it." Each stored secret is something to protect, clear, and migrate. Store the minimum.
Applying the rule to an example app
Imagine a note-taking app with sign-in, an offline cache, and a setting for dark mode.
- The refresh token goes in secure storage.
- The access token stays in memory.
- The cache of notes goes in an encrypted database, and the database key goes in secure storage.
- The dark mode flag goes in
shared_preferences. - The app's analytics key is a public write-only key. It is not a user secret, so it can live in the code. Anything that would grant real power should stay on the server.
That leaves two entries in the vault, which is the right size for most apps.
Exercise
A fitness app signs users in with an OAuth server. It receives a 15-minute access token and a 60-day refresh token. It also caches the user's last 500 workouts as JSON for offline viewing and stores a "metric or imperial" setting. The developer also wants to save the user's password so the app can sign in again silently. For each of these five items, say where it should be kept and why.
Show answer
Refresh token: secure storage, because it is secret, small, and must persist across launches. Access token: in memory, since it expires in 15 minutes and can be renewed from the refresh token (persisting it is an acceptable trade-off only if you clear it on sign-out). Workout cache: a database or file, encrypted if the data is sensitive, with its key in secure storage, because 500 records are too large and need querying. Metric or imperial setting: shared_preferences, because it is not a secret. Password: do not store it. Use the refresh token for silent sign-in, since a token can be revoked and a password may work on other sites.
Exercise
A teammate proposes writing the app's third-party payment API secret into secure storage on first launch, so that it is "hidden from users." Is this a good use of the package? What should the team do instead?
Show answer
No. The secret must be present in the app code or assets to be written on first launch, and anyone can extract it from the app binary, so secure storage adds no protection. The team should keep the secret on their own server and have the app call a server endpoint that uses it on the app's behalf.