Hardening a Flutter app's auth: secure token storage, no tokens in logs, Android backup off
The second pass on a Flutter app's token handling after a security review: flutter_secure_storage options that matter, a migration that checks its own write, a logging interceptor that redacts headers and is off in release, backup rules for Android 12, and how to verify each on a release APK.
Our VAPT had four findings on the Flutter app: tokens in SharedPreferences, the bearer token in device logs, allowBackup not set, and no network security config. I wrote up the basic fixes in storing auth tokens securely in a Flutter app on Android. This post is the second pass. The first re-test closed only two of the four, and the gap between "we added flutter_secure_storage" and "the finding is closed" was bigger than I expected.
In the first re-run, backup and the network config were closed. Token storage was marked partial (the package was a dependency, but the token service still wrote to SharedPreferences). The logging finding was still open, with six Log.d lines in the auth interceptor that printed token values, and debug logging defaulting to on. All four were closed in the re-test after that, and have held in every run since.
Here is what changed between "partial" and "closed", and how I check each one on a release build.
Secure storage options that actually matter
const FlutterSecureStorage() with no options works, but the defaults are not what I wanted on either platform. This is the store we ended up with, on flutter_secure_storage 9.2.4:
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class SecureTokenStore {
SecureTokenStore._();
static const FlutterSecureStorage _storage = FlutterSecureStorage(
aOptions: AndroidOptions(
// API 23+ EncryptedSharedPreferences instead of legacy per-value RSA.
encryptedSharedPreferences: true,
// Without this, an invalidated Keystore key throws on every read forever.
resetOnError: true,
),
iOptions: IOSOptions(
// Readable after the first unlock, never synced to iCloud or another device.
accessibility: KeychainAccessibility.first_unlock_this_device,
),
);
/// Null means the store is unusable; an empty map means it works but is empty.
static Future<Map<String, String>?> readAll(List<String> keys) async {
final values = <String, String>{};
try {
for (final key in keys) {
final value = await _storage.read(key: key);
if (value != null && value.isNotEmpty) values[key] = value;
}
return values;
} catch (_) {
return null;
}
}
static Future<String?> read(String key) async {
try {
return await _storage.read(key: key);
} catch (_) {
return null;
}
}
static Future<bool> write(String key, String value) async {
try {
await _storage.write(key: key, value: value);
return true;
} catch (_) {
return false;
}
}
}
resetOnError is the one people skip. On some devices the Keystore key goes bad (the package's issue tracker has plenty of reports after restores and OS updates), and after that every read throws. With reset on, the store wipes itself and the user logs in again. Without it, the user is basically stuck until they clear app data.
first_unlock_this_device is the iOS side. The token is readable after the phone is unlocked once since boot, so background refresh still works, and the this_device part means it never goes to an iCloud Keychain backup.
A version note. In flutter_secure_storage 10.0.0 the encryptedSharedPreferences option was deprecated (the Jetpack Security crypto library it depends on was deprecated), and 11.x removed it. On 10 and above the package migrates existing data for you when migrateOnAlgorithmChange is true. So if you copy the snippet above onto 11, it won't compile; drop that line.
The readAll returning null versus an empty map is small but I like it. "The store is broken" and "the user is logged out" are different states, and the caller should not treat them the same.
A migration that checks its own write
The reason storage was only "partial" was the migration. Existing users had tokens in SharedPreferences. Copying them over and deleting the old copy sounds like three lines. But if the secure write fails silently and you delete the old copy anyway, the user is logged out for no reason. And if you never delete, the plaintext copy stays forever.
So the migration writes, reads it back, and deletes the legacy copy only when the read matches:
import 'package:shared_preferences/shared_preferences.dart';
const tokenKeys = ['access_token', 'refresh_token'];
Future<void> migrateLegacyTokens(SharedPreferences prefs) async {
final current = await SecureTokenStore.readAll(tokenKeys);
if (current == null) return; // store unusable now; try again next launch
for (final key in tokenKeys) {
final legacy = prefs.getString(key);
if (legacy == null || legacy.isEmpty) continue;
if (!current.containsKey(key)) {
if (!await SecureTokenStore.write(key, legacy)) continue;
if (await SecureTokenStore.read(key) != legacy) continue;
}
await prefs.remove(key);
}
}
Run it once at start-up, before anything read a token. On logout, clear both places. The old copy should be gone already, but clearing it costs nothing.
No tokens in logs, and logging off in release
The six log lines were the easy part. The interceptor now prints the path only: Using customer access token for: /v1/users/me, never the value. The harder part was that logging was on in release builds itself.
The fix was making the default depend on the build mode. kReleaseMode is a compile-time constant, so this is still a const:
import 'package:flutter/foundation.dart';
class Env {
/// Off in release builds; --dart-define=ENABLE_DEBUG_LOGGING=true still overrides.
static const bool enableDebugLogging = bool.fromEnvironment(
'ENABLE_DEBUG_LOGGING',
defaultValue: !kReleaseMode,
);
}
Then the HTTP logging interceptor checks the flag before building any strings, and replaces credential headers instead of trimming them:
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
class LoggingInterceptor extends Interceptor {
LoggingInterceptor({bool? enabled}) : _enabled = enabled ?? Env.enableDebugLogging;
final bool _enabled;
static const Set<String> _redacted = {
'authorization',
'proxy-authorization',
'cookie',
'set-cookie',
'x-api-key',
};
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
if (_enabled) {
final headers = options.headers.map(
(k, v) => MapEntry(k, _redacted.contains(k.toLowerCase()) ? '<redacted>' : v),
);
debugPrint('REQUEST[${options.method}] ${options.path} $headers');
}
handler.next(options);
}
}
Why check _enabled here when the logger already drops debug messages in release? Because the logger drops the message only after the string interpolation has run. A Map.toString() of a big response body on every request, on the UI thread, for a message nobody sees. That was a small performance win we got for free.
Backup off, including Android 12 device transfer
android:allowBackup="false" was already in the manifest after the first round. What I also added was dataExtractionRules. On Android 12 and above, Google's own behaviour-changes page says that on some devices allowBackup="false" disables Google Drive backup but not device-to-device transfer. The new rules file covers both:
<?xml version="1.0" encoding="utf-8"?>
<data-extraction-rules>
<cloud-backup>
<exclude domain="root" />
<exclude domain="file" />
<exclude domain="database" />
<exclude domain="sharedpref" />
<exclude domain="external" />
</cloud-backup>
<device-transfer>
<exclude domain="root" />
<exclude domain="file" />
<exclude domain="database" />
<exclude domain="sharedpref" />
<exclude domain="external" />
</device-transfer>
</data-extraction-rules>
It goes in res/xml/data_extraction_rules.xml and the manifest points to it with android:dataExtractionRules="@xml/data_extraction_rules", next to allowBackup.
Network security config, and why no pinning
The config is plain: cleartext off, system CAs only. The one extra is a debug-overrides block that trusts user CAs, so a proxy like mitmproxy still works on debug builds. Release builds ignore that block.
<network-security-config>
<base-config cleartextTrafficPermitted="false">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
<debug-overrides>
<trust-anchors>
<certificates src="system" />
<certificates src="user" />
</trust-anchors>
</debug-overrides>
</network-security-config>
We decided against certificate pinning on purpose, and wrote the reason into the file as a comment. The API sits behind a load balancer with an ACM certificate that renews itself. A pin on that certificate would brick every installed app on the day it rotates. The reviewer accepted that as a documented decision.
Checking each fix on a release APK
None of this counts until it is checked on the build users actually get. These need the Android SDK command line tools:
flutter build apk --release
APK=build/app/outputs/flutter-apk/app-release.apk
apkanalyzer manifest debuggable "$APK" # want: false
apkanalyzer manifest target-sdk "$APK"
apkanalyzer manifest print "$APK" \
| grep -E 'allowBackup|dataExtractionRules|networkSecurityConfig|usesCleartextTraffic'
You want allowBackup="false", both config references, and no usesCleartextTraffic line.
For backups, adb backup is not much of a test any more. Since Android 12, for apps targeting API 31 or higher it leaves app data out unless the app is debuggable. So the manifest check above is the real check.
For logs, install the release build on an emulator, log in, use the app for a minute, and grep:
adb logcat -d | grep -iE 'bearer|authorization|access_token' || echo "nothing found"
And for storage, a release build is not debuggable, so adb shell run-as <your.package> fails with "package not debuggable". That is what you want. On a debug build of the same code, run-as and cat shared_prefs/*.xml should show no token after the migration has run.
There we have it: the re-test after that marked all four closed. If you have doubts about any of the checks, drop a comment.