Sub topic 9
Reinstalls, backups and sign-out
This chapter assumes you have read the earlier chapters. You should know the basic flutter_secure_storage operations and have a TokenRepository like the one built earlier. It covers three situations where stored secrets behave in ways that surprise people: the app is uninstalled and installed again, the device is restored from a backup, and the user signs out.
Why these three events cause bugs
Secure storage is not a single place on the device. On iOS the data lives in the Keychain, which the operating system manages separately from your app's files. On Android the encrypted values live in a file inside your app's data, and the key that decrypts them lives in the Android Keystore. Each platform handles uninstalls and backups differently, so the same code can behave differently on each.
The result is two opposite failure modes:
- Stale data survives. A new install finds an old refresh token and the user appears signed in when they should not be.
- Data is present but unreadable. Encrypted values come back from a backup, but the key that decrypts them did not, so every read fails.
What happens on reinstall
| Platform | Uninstall the app | Result after reinstall |
|---|---|---|
| iOS | Keychain items usually stay on the device | The old token may still be there |
| Android | App data is deleted, including the encrypted file | Storage is empty, and the user signs in again |
On iOS, Keychain items are not tied to the app's file sandbox. In practice they commonly survive an uninstall. Apple does not promise this, so treat it as likely behavior, not a guarantee. The consequence is that a user who deletes your app and reinstalls it may be signed in without entering credentials. Some teams accept this. Others see it as a security or privacy problem, especially on shared or resold devices.
Clearing the Keychain on a fresh install
Ordinary app preferences, such as those stored with shared_preferences, are deleted on uninstall. You can use that difference to detect a fresh install. Keep a flag in preferences. If the flag is missing, the app has just been installed, so any secrets that exist must be left over.
This example uses the shared_preferences package, which you add with flutter pub add shared_preferences.
import 'package:flutter/widgets.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _storage = FlutterSecureStorage();
Future<void> clearSecretsOnFreshInstall() async {
final prefs = await SharedPreferences.getInstance();
const flag = 'has_run_before';
if (prefs.getBool(flag) ?? false) return;
await _storage.deleteAll();
await prefs.setBool(flag, true);
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await clearSecretsOnFreshInstall();
runApp(const Placeholder());
}Run this before any code reads the token. If the check ran after the first read, the app could briefly treat a stale token as valid.
What happens with backups
Backups are the harder problem, because they can move encrypted data to a place where it cannot be decrypted.
Android Auto Backup
Android's Auto Backup can copy an app's files to the user's cloud account and restore them on a new install or a new phone. The encrypted values live in a shared preferences file, so they can be included in that backup. The Keystore key is different. It is hardware-bound or device-bound and is not part of the backup.
After a restore, the app has ciphertext but no matching key. Reads then fail with a PlatformException, often wrapping an error from the Java cryptography layer such as a bad padding or invalid key message. Because it happens after a restore, you may not see it during development, and users report it as "the app crashes after I got a new phone".
The fix is to exclude the secure storage file from backups. There are two backup configurations, one for Android 11 and below and one for Android 12 and above. Declare both in AndroidManifest.xml:
<application
android:fullBackupContent="@xml/backup_rules"
android:dataExtractionRules="@xml/data_extraction_rules"
...>Then create android/app/src/main/res/xml/backup_rules.xml:
<?xml version="1.0" encoding="utf-8"?>
<full-backup-content>
<include domain="sharedpref" path="."/>
<exclude domain="sharedpref" path="FlutterSecureStorage"/>
</full-backup-content>And android/app/src/main/res/xml/data_extraction_rules.xml:
<?xml version="1.0" encoding="utf-8"?>
<data-extraction-rules>
<cloud-backup>
<include domain="sharedpref" path="."/>
<exclude domain="sharedpref" path="FlutterSecureStorage"/>
</cloud-backup>
<device-transfer>
<include domain="sharedpref" path="."/>
<exclude domain="sharedpref" path="FlutterSecureStorage"/>
</device-transfer>
</data-extraction-rules>The simpler option is android:allowBackup="false". It turns off backup for the entire app, which also removes backups of data you may want to keep. Choose it only if nothing else in the app benefits from backup.
iOS backups and device migration
Keychain items are included in encrypted device backups. Whether they transfer to a different device depends on the accessibility level you chose. The _this_device variants never leave the device they were created on.
| Accessibility value | Readable | Migrates to a new device |
|---|---|---|
| `unlocked` | While the device is unlocked | Yes |
| `unlocked_this_device` | While the device is unlocked | No |
| `first_unlock` | After first unlock since boot | Yes |
| `first_unlock_this_device` | After first unlock since boot | No |
For tokens that the server can re-issue, prefer a _this_device value. A token that moved to a second device can look like a suspicious session, and the user can simply sign in again. Note that first_unlock suits background work such as push-triggered refreshes, while unlocked blocks reads when the phone is locked.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
const storage = FlutterSecureStorage(
iOptions: IOSOptions(
accessibility: KeychainAccessibility.first_unlock_this_device,
),
);Changing the accessibility level of an existing app affects only items written afterward. If you change it in an update, read the old value and write it again, or users will keep the old setting.
Treat unreadable data as signed out
Whatever you do to prevent it, unreadable data will still occur occasionally. A user may restore an old backup, or the Keystore may be reset after a lock screen change on some devices. The repository from the earlier chapter already handles this by catching PlatformException, wiping storage and returning null. The calling code then sees "no token" and shows the sign-in screen, which is the correct recovery.
The key design point is that "no token" and "unreadable token" lead to the same state. Do not show the user an error dialog for this. They cannot act on it, and signing in again fixes the problem.
Signing out properly
Sign-out must remove secrets from the device, and it should also end the session on the server. The order matters.
The code below puts the local deletion in a finally block, so a network failure cannot leave the user signed in on the device.
abstract class AuthApi {
Future<void> revoke(String refreshToken);
}
class AuthService {
AuthService(this._api, this._tokens);
final AuthApi _api;
final TokenRepository _tokens;
Future<void> signOut() async {
final token = await _tokens.readRefreshToken();
try {
if (token != null) {
await _api.revoke(token);
}
} catch (_) {
// The server could not be reached. The token will expire on its own,
// and the user must still be signed out locally.
} finally {
await _tokens.clear();
}
}
}delete or deleteAll
- Use
delete(key: ...)when your app stores other values in the same storage that should outlive a sign-out, such as a device identifier or a "remember my email" value. - Use
deleteAll()when everything in the storage belongs to the signed-in user. It is also the right call in the error-recovery path above.
If a user can switch between accounts, include the user ID in the key name, for example refresh_token_$userId. Then signing out one account does not touch another account's token.
Other places a session leaks
Clearing secure storage is not the end of sign-out. Also check:
- In-memory copies, such as an HTTP client that still holds an
Authorizationheader. - Cached user data on disk, for example in a local database or image cache.
- State management objects that still hold the user profile.
A common bug is clearing the token while an interceptor keeps sending the old access token until the app restarts.
Summary of decisions
| Situation | Platform | Action |
|---|---|---|
| Token survives reinstall | iOS | Fresh-install flag, then `deleteAll()` |
| Restored ciphertext cannot be decrypted | Android | Exclude the file from backup rules |
| Token copied to a new phone | iOS | Use a `_this_device` accessibility value |
| Read throws `PlatformException` | Both | Wipe storage, return `null`, show sign-in |
| User signs out | Both | Revoke on server, delete locally in `finally` |
Exercise
A user restores their Android phone from a cloud backup onto a new device. Your app now throws a PlatformException every time it reads the refresh token. What caused it, and what are two changes that fix it?
Show answer
The backup restored the encrypted shared preferences file, but the Android Keystore key that encrypts it does not travel with backups, so the ciphertext cannot be decrypted. The first fix is to exclude the secure storage file from backup in both backuprules.xml and dataextraction_rules.xml. The second is to catch PlatformException in the repository, call deleteAll() and return null so the app shows the sign-in screen.
Exercise
Why does signOut put the call to the local token deletion in a finally block instead of after the revoke call?
Show answer
If the revoke request throws, for example because the device is offline, code placed after it would be skipped and the token would stay on the device. A finally block runs whether the request succeeds or fails, so the user is always signed out locally.
Exercise
On iOS, a user deletes your app and installs it again, and is signed in without entering a password. Explain why, and describe how to prevent it.
Show answer
Keychain items are stored outside the app's sandbox and commonly survive an uninstall. To prevent it, keep a flag in shared_preferences, which is deleted on uninstall. At startup, if the flag is missing, call deleteAll() on the secure storage and then set the flag.