Sub topic 7
Keychain accessibility and Android options
This chapter covers the two settings that most affect how flutter_secure_storage behaves on a real device: the iOS Keychain accessibility level and the Android storage options. It assumes you have already added the package and can call write, read and delete. You should also know what a refresh token is and why an app keeps one.
Why options matter
The defaults work in a simple app that only reads tokens while the user has the app open. Problems appear when something reads a secret at an unexpected moment. Examples are a background fetch while the phone is locked, a restore onto a new phone, or an Android upgrade that changes the storage format. Options let you decide when a value can be read and where it can travel.
Options are passed to the FlutterSecureStorage constructor. Each platform has its own options class, and the package ignores the classes for platforms you are not running on.
| Platform | Options class | Passed as |
|---|---|---|
| iOS | `IOSOptions` | `iOptions` |
| Android | `AndroidOptions` | `aOptions` |
| macOS | `MacOsOptions` | `mOptions` |
| Web | `WebOptions` | `webOptions` |
| Linux | `LinuxOptions` | `lOptions` |
| Windows | `WindowsOptions` | `wOptions` |
This chapter covers iOS and Android. Web and desktop are covered in a later chapter.
iOS: Keychain accessibility
Every Keychain item carries an accessibility attribute. It tells iOS when the item may be decrypted. You set it with KeychainAccessibility in IOSOptions.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
const storage = FlutterSecureStorage(
iOptions: IOSOptions(
accessibility: KeychainAccessibility.first_unlock,
),
);The package offers five levels.
| Value | Readable when | Included in device migration |
|---|---|---|
| `unlocked` | The device is unlocked. This is the default. | Yes |
| `unlocked_this_device` | The device is unlocked. | No |
| `first_unlock` | After the first unlock since boot, including while locked later. | Yes |
| `first_unlock_this_device` | After the first unlock since boot. | No |
| `passcode` | The device is unlocked and has a passcode set. | No |
The "this device" variants, and passcode, are never copied to a new phone through an encrypted backup or restore. The other levels may be.
Choosing a level
The deciding question is whether your app ever needs the secret when the screen is locked.
A few cases show how this works in practice:
- Push notifications or background sync. If your app wakes in the background and uses a token to call your server, the phone may be locked. With
unlocked, the read fails. Usefirst_unlock. - A banking-style app that only works in the foreground. Use
unlocked_this_device. The token stays on the phone it was created on, and a restored phone makes the user sign in again. - A secret that must not exist without a lock screen. Use
passcode. Writing fails if no passcode is set. iOS also deletes the item if the user later removes the passcode.
Gotchas with accessibility
- The accessibility level is fixed when the item is written. Changing the constructor option later does not rewrite items that already exist. To change the level for existing users, read the value, delete it, and write it again with the new options.
first_unlockstill needs a first unlock. After a reboot, a background launch can happen before the user has unlocked the phone. Reads fail until then. Handle that failure as described in the error handling chapter.- A failed read is not the same as a missing key. An item that exists but is not yet readable can surface as an error rather than
null. Do not treat every failure as "signed out" without thinking.
Other iOS options
IOSOptions has several other fields. Their names and defaults have changed between versions, so check the README for your installed version.
accountNamesets the Keychain service name used to namespace your items. Keep it stable once you ship. Changing it hides existing items from your app.groupIdis the Keychain access group. Set it to share items between your app and an extension or a sibling app. The group must also be enabled in the app's entitlements, or reads and writes fail.synchronizablestores items in iCloud Keychain so they follow the user's Apple ID to other devices. For auth tokens this is usually unwanted. Leave it off unless you have a specific reason.
macOS uses the same ideas through MacOsOptions.
Android: storage options
Android has no Keychain. The package encrypts values with a key held in the Android Keystore and keeps the encrypted data in app-private storage. AndroidOptions controls how that encryption is done.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
const storage = FlutterSecureStorage(
aOptions: AndroidOptions(
encryptedSharedPreferences: true,
),
);The encryptedSharedPreferences flag
In package version 9 and earlier, encryptedSharedPreferences: true stores data through Jetpack's EncryptedSharedPreferences. Without it, the package uses its own cipher implementation over regular preferences. The two modes use different storage files. If you flip the flag on an app that already has users, the new mode cannot see what the old mode wrote. Those users appear signed out.
Newer major versions of the package deprecate this flag and use their own ciphers, because Google deprecated the Jetpack security library. Some versions migrate old data automatically. Others ignore the flag. Check the changelog and README for your version before relying on it, and run an upgrade test with data written by the previous release.
Minimum API level
Keystore-backed encryption needs a minimum Android API level, and it is higher when encryptedSharedPreferences is on. The exact numbers depend on the package version. Set minSdkVersion in android/app/build.gradle to the value the README of your version requires. A build that fails with a manifest merger error mentioning minSdkVersion usually means this setting is too low.
The resetOnError option
Some package versions include resetOnError in AndroidOptions. When enabled, the package deletes all stored data if decryption fails, instead of throwing. Decryption can fail after a restore from backup, because the Keystore key does not move between devices but the encrypted file might. Resetting turns that situation into a clean signed-out state.
The drawback is silent data loss: one decryption failure erases every value in the store, not just the broken one. If you keep several secrets, prefer to catch the error yourself and decide what to delete.
Backups on Android
Android can back up app data to Google Drive. The encrypted file may be backed up, but the Keystore key is not. After a restore, the file exists and cannot be decrypted. Exclude the secure storage file from backup, or turn backups off for the app, in AndroidManifest.xml:
<application
android:allowBackup="false"
android:label="my_app">
<!-- activities omitted -->
</application>If you need backups for other data, use backup rules to exclude only the secure storage files. The lifecycle chapter covers this in more detail.
Setting options in one place
Putting the options in a single factory means every call site uses the same configuration. Mixing options between calls is a common source of "the value is there but I can't read it" bugs.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
FlutterSecureStorage createSecureStorage() {
return const FlutterSecureStorage(
iOptions: IOSOptions(
accessibility: KeychainAccessibility.first_unlock,
),
aOptions: AndroidOptions(
encryptedSharedPreferences: true,
),
);
}
Future<void> main() async {
final storage = createSecureStorage();
await storage.write(key: 'refresh_token', value: 'abc123');
print(await storage.read(key: 'refresh_token'));
}You can also pass options to a single call, for example storage.read(key: 'k', iOptions: ...). This overrides the constructor options for that call only. Use it sparingly. A value written under one configuration and read under another can end up in a different location or fail to decrypt.
Common errors
| Symptom | Likely cause |
|---|---|
| Reads work in the foreground but fail in a background task on iOS | Accessibility is `unlocked`. Switch to `first_unlock` for new writes. |
| Users are signed out after an app update on Android | `encryptedSharedPreferences` was changed, or the package major version changed its storage format. |
| `PlatformException` on first read after a restore | The Keystore key or Keychain item did not move with the data. Clear the store and sign in again. |
| iOS write fails with `passcode` | The device has no passcode set. Catch the error and ask the user to enable one, or fall back. |
| Shared Keychain items are not visible to an extension | The `groupId` is missing from `IOSOptions` or the entitlements. |
| Android build fails on `minSdkVersion` | The app's minimum API level is below what the package requires. |
Summary
Accessibility on iOS decides when a secret can be read and whether it travels to new devices, and it is fixed at write time. Android options decide which storage format is used, and changing them between releases strands existing data. Define the options once, test upgrades with real stored data, and keep backups from copying encrypted files without their keys.
Exercise
Your app uses a token during background sync while the phone is locked. It currently stores the token with the default iOS accessibility, and background sync fails with read errors. You change the constructor to use KeychainAccessibility.first_unlock and ship an update. Existing users still see failures. Why, and how do you fix it for them?
Show answer
Accessibility is stored on each Keychain item when it is written, so items written under the default (unlocked) level keep that level after the update. Only new writes use first_unlock. To fix existing users, run a one-time migration at startup that reads the token, deletes it, and writes it again with the new options (read may fail while locked, so do it when the app is in the foreground and the device is unlocked). Alternatively, ask users to sign in again so the token is rewritten.
Exercise
A team toggles encryptedSharedPreferences from false to true in a release. After the update, Android users are all signed out, but iOS users are not. What happened, and what should the team have done?
Show answer
On Android the flag selects a different storage backend and file, so the new mode cannot find values written by the old mode. iOS does not use that flag, so it is unaffected. The team should have treated the change as a migration: read the token with the old options, write it with the new options, then delete the old value. They should have tested an in-place upgrade from the previous release before shipping.