Sub topic 12
Web and desktop considerations
This chapter covers what changes when you run flutter_secure_storage outside Android and iOS. It assumes you have finished the earlier chapters: you know the write, read and delete API, the TokenRepository pattern, and the threat model for on-device secrets. You should also know how to build a Flutter app for at least one desktop or web target.
The package builds for web, macOS, Linux and Windows, and the API is the same on every platform. The protection behind that API is not. On a phone, the operating system offers hardware-backed key storage. On desktop the backing store depends on the OS and its configuration. On the web, the backing store is the browser, and the browser is a much weaker place for a secret.
The same API, different guarantees
The table below summarizes where values end up. Treat it as a map and check the package README for the current details, because these backends have changed between major versions.
| Platform | Backing store | Main caveat |
|---|---|---|
| iOS | Keychain | Accessibility setting decides when items can be read |
| Android | Keystore-protected key, encrypted data in app storage | Backup and reinstall behavior |
| macOS | Keychain | Entitlements and signing affect access |
| Linux | libsecret, which talks to a keyring service | A keyring daemon must be installed and unlocked |
| Windows | Data encrypted with the Windows Data Protection API (DPAPI) | Protection is tied to the user account, not to your app |
| Web | Browser storage, values encrypted with the WebCrypto API | Scripts on your own origin can use the key |
The important difference is who can read the secret. On iOS and Android, other apps are sandboxed away from your data. On Windows, DPAPI protects against other users, but any process running as the same user can generally ask Windows to decrypt the data. On the web, any JavaScript running on your page can read what your app can read.
Web
The web implementation is the one to be most careful with. It encrypts values using the browser's WebCrypto API and writes the result to browser storage such as localStorage. The README has described this implementation as experimental, so read its current wording before you depend on it.
The point of encryption is to protect data at rest, but here the code that decrypts the data runs in the same page as everything else. Two consequences follow:
- A cross-site scripting (XSS) bug lets an attacker's script call the same code paths, or read the same storage, that your app uses. Encryption does not stop that.
- Anyone with access to the browser profile on disk, or to the developer tools on that machine, sees the same data the page sees.
Other practical points:
- The browser needs WebCrypto, which requires a secure context. Serve the app over HTTPS in production.
localhostis treated as secure for development. - Storage is scoped to the origin (scheme, host and port). A change of domain or port makes previously stored values invisible.
- If the encryption key and the stored data get out of sync, for example because the user cleared only part of the site data, a read fails to decrypt. Handle that as you handled unreadable data in the error-handling chapter: treat it as signed out.
- Private browsing windows and "clear site data on exit" settings delete values. Do not assume a token survives.
You can set a database name and key-related options through WebOptions. Setting a distinct dbName keeps your app's entries separate from other apps on the same origin, which matters during development when many projects share localhost.
What to do with tokens on the web
For web builds, the safest design is usually to keep long-lived secrets out of Dart entirely. A common approach is to have your backend set the refresh token in an HttpOnly, Secure, SameSite cookie. The browser sends it automatically and scripts cannot read it. Your Dart code then holds only a short-lived access token in memory. When the page reloads, the app asks the backend for a new access token and the cookie does the authentication.
This changes your repository. On the web it may store nothing at all. The code below keeps that decision in one place.
import 'package:flutter/foundation.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
/// Builds a storage instance with options for every platform.
/// Options for platforms that are not running are ignored.
FlutterSecureStorage createStorage() {
return const FlutterSecureStorage(
iOptions: IOSOptions(
accessibility: KeychainAccessibility.first_unlock,
),
mOptions: MacOsOptions(
accessibility: KeychainAccessibility.first_unlock,
),
webOptions: WebOptions(
dbName: 'my_app_secure_db',
publicKey: 'my_app_secure_key',
),
);
}
/// Policy: do not persist the refresh token in the browser.
bool get shouldPersistRefreshToken => !kIsWeb;A repository can then consult shouldPersistRefreshToken before it calls write. The rest of the app does not need to know which platform it is on.
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class WebAwareTokenRepository {
WebAwareTokenRepository({
required FlutterSecureStorage storage,
required bool persist,
}) : _storage = storage,
_persist = persist;
static const _refreshKey = 'refresh_token';
final FlutterSecureStorage _storage;
final bool _persist;
Future<void> saveRefreshToken(String token) async {
if (!_persist) return; // the server keeps it in an HttpOnly cookie
await _storage.write(key: _refreshKey, value: token);
}
Future<String?> readRefreshToken() async {
if (!_persist) return null;
return _storage.read(key: _refreshKey);
}
Future<void> clear() => _storage.delete(key: _refreshKey);
}Wire it up with WebAwareTokenRepository(storage: createStorage(), persist: shouldPersistRefreshToken). Passing persist in as a constructor argument keeps the repository testable on any platform, because a test can pass either value without faking kIsWeb.
macOS
macOS uses the Keychain, as iOS does, so the accessibility option you saw earlier applies through MacOsOptions. The difference is in app setup.
- A sandboxed macOS app needs the Keychain entitlement in both
DebugProfile.entitlementsandRelease.entitlements. The README describes the exact key to add. Without it, writes fail with aPlatformException, often showing an error code related to missing entitlements. - Debug builds that are not signed with a development team can behave differently from signed release builds. Test a signed build before you ship.
- Items written by a differently signed build may not be readable by a new build. This shows up as a read error after you change your signing identity.
Linux
On Linux the package uses libsecret, which talks to a keyring service such as GNOME Keyring or KWallet through the Secret Service interface.
- Install the development packages when you build. The README lists them, and they include
libsecret-1-dev. A missing package shows up as a CMake or compile error, not a Dart error. - At runtime a keyring service must be running and unlocked. On a minimal install, a container, a remote session or a CI runner there may be none. Calls then fail with a
PlatformException. - Users who log in automatically can have a keyring that is locked until they enter a password, so the first read can prompt or fail.
Because the failure depends on the user's machine and not on your code, probe for a working store at startup and decide what to do before the first real write.
import 'package:flutter/services.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
/// Returns true if the platform store accepts a write, read and delete.
Future<bool> isSecureStorageAvailable(FlutterSecureStorage storage) async {
const probeKey = '__probe__';
try {
await storage.write(key: probeKey, value: 'ok');
final value = await storage.read(key: probeKey);
await storage.delete(key: probeKey);
return value == 'ok';
} on PlatformException {
return false;
}
}If the probe returns false, do not fall back to a plain file without telling the user. Reasonable choices are to keep the token in memory only and ask the user to sign in again next launch, or to show a message explaining that no keyring was found.
Windows
The Windows build encrypts values with the Windows Data Protection API and stores the result in a file under the user's profile. Check the README for the current storage details, since earlier versions used a different mechanism and a major upgrade may not read old data.
- You need Visual Studio with the C++ desktop workload, including the ATL component, to build the plugin. A missing ATL component is a common reason the first Windows build fails.
- DPAPI ties data to the Windows user account. Another user on the same machine cannot decrypt it, but another program running as the same user usually can. This is weaker isolation than on a phone.
- If the user profile is migrated, or the password is reset by an administrator, the data may become unreadable. Handle that as stale data and ask for a new sign-in.
Choosing a policy per platform
A single policy table in your app is easier to review than checks scattered through the code. Write down what each platform may store and who is responsible when storage is missing.
| Platform | Refresh token | Access token | If storage is unavailable |
|---|---|---|---|
| iOS, Android | Secure storage | Memory | Treat as signed out |
| macOS | Secure storage | Memory | Treat as signed out |
| Windows | Secure storage | Memory | Treat as signed out |
| Linux | Secure storage if the probe passes | Memory | Memory only, warn the user |
| Web | HttpOnly cookie, not Dart | Memory | Sign in again on reload |
Testing across platforms
The setMockInitialValues approach from the testing chapter replaces the platform channel, so it runs the same way for all targets in unit tests. It cannot tell you whether the Linux keyring is present or whether the macOS entitlement is correct. For those, run a small integration test on each target, or at minimum run the probe function above on a real machine of each type before a release. Keep the persist flag injectable so that unit tests cover both the web and non-web branches.
Common mistakes
- Assuming the web build is as protected as the mobile build and storing a long-lived refresh token in it.
- Forgetting the macOS entitlement, then seeing writes fail only in release builds.
- Building on Linux CI without the libsecret development package, or running tests that need a real keyring in a container without one.
- Changing the web
dbNameor the origin between releases, which makes existing values unreadable. - Letting a failed write on desktop go unnoticed. A write that throws inside an unawaited future is lost silently, so always
awaitstorage calls.
Exercise
Your Flutter app targets Android, iOS and web. The backend can set an HttpOnly cookie that holds the refresh token. Where should the refresh token live on each platform, and what should the web build keep in Dart?
Show answer
On Android and iOS, store the refresh token with fluttersecurestorage so it lands in the Keystore-backed store or the Keychain. On the web, do not store it in Dart or in fluttersecurestorage. Let the backend keep it in an HttpOnly, Secure cookie, so scripts cannot read it. The web build keeps only a short-lived access token in memory, and after a reload it asks the backend for a new one, which the cookie authenticates.
Exercise
A user reports that your Linux desktop app signs them out on every launch, and logs show a PlatformException on write. Give two likely causes and one change to the app that makes the failure visible and safe.
Show answer
Likely causes are that no Secret Service keyring daemon is running (for example in a container or minimal install), or that the keyring is locked and was not unlocked at login. Run a startup probe that writes, reads and deletes a test key, and if it fails, keep the token in memory only and show the user a message that explains secure storage is unavailable, instead of silently dropping the token.