Skip to content
Tutorials Center
My learning

Topics

Lesson 59 of 73 ยท Quality and performance

Security in Flutter Apps

Secure your Flutter app: why secrets in the binary are not secret, obfuscation limits, secure storage, certificate pinning, token handling and input validation.

A mobile app runs on a device you do not control. The user owns the phone, and a determined person can unpack your app, read its files, watch its network traffic and change its behavior. That one fact shapes mobile security: you cannot hide anything from the person holding the device, so you decide carefully what the app contains, what it stores, and what your server must always check for itself.

This lesson covers the practical rules for Flutter apps: secrets in binaries, what obfuscation does and does not do, secure storage, certificate pinning, handling auth tokens, and validating input.

Real vs stand-in. Dart, YAML and shell snippets are real and read-only, because the site has no Flutter runtime or device keystore. The live examples are JavaScript stand-ins that demonstrate the ideas: reading a "secret" from a binary, token expiry, pinning by fingerprint and input validation.

The golden rule

The device is hostile Users can inspect everything on it.
The server decides Never trust the client alone.

Client checks improve UX. Server checks provide security.

1 / 2

Secrets in the binary are not secret

Anything compiled into your app can be extracted: string constants, API keys, passwords, private URLs. An APK is a zip file; an iOS app can be decrypted on a jailbroken device. Tools list every string in minutes.

DART
// Do NOT do this. The key ships to every user.
const stripeSecretKey = 'sk_live_51H...';
const adminPassword = 'letmein';

Using --dart-define or a .env file keeps the key out of source control, which is good, but the value is still baked into the binary at build time and is just as readable:

Terminal
flutter build apk --dart-define=MAPS_KEY=abc123

So split what you embed into two groups:

  • Public identifiers are fine in the app: a Firebase project config, a Maps key that is restricted to your app's package name and signing certificate, an analytics id. Restrict them in the provider's console so a copy is useless elsewhere.
  • True secrets must never ship: payment secret keys, database passwords, private signing keys, third-party API keys that bill you per call. Put them on your server. The app calls your server with the user's own credentials, and the server calls the third party.
JS Finding a secret in a 'compiled' app

Press Run (or Ctrl + Enter) to see the console output here.

No output.

No cleverness was needed: a secret stored as plain text is found by a program that is a few lines long. Splitting the string or XOR-ing it only slows an attacker by minutes. The only real fix is not to ship it.

Obfuscation: useful, but not protection

Release builds can scramble class and function names:

Terminal
flutter build apk --obfuscate --split-debug-info=build/symbols
flutter build ipa --obfuscate --split-debug-info=build/symbols

--obfuscate renames Dart identifiers, which makes reverse-engineering your logic harder and shrinks the binary slightly. --split-debug-info moves the debug symbols into files you keep (upload them to your crash reporter) so stack traces can be decoded.

It does not encrypt strings, hide network calls, or stop anyone from reading your assets. Treat obfuscation as a speed bump for copying your code, never as a lock on secrets. Android builds can also be shrunk with R8 and configured through ProGuard rules for native plugins.

Secure storage

Where you save data matters. SharedPreferences writes plain text into app storage, which is readable on rooted or jailbroken devices and in backups. For tokens and small secrets, use the platform's protected store through flutter_secure_storage:

DART
const storage = FlutterSecureStorage();

await storage.write(key: 'refresh_token', value: token);
final saved = await storage.read(key: 'refresh_token');
await storage.delete(key: 'refresh_token');

On iOS it uses the Keychain, on Android the Keystore (the encryption key lives in hardware-backed storage where available). It is meant for small values like tokens and keys, not for databases; for an encrypted database use a library that supports encryption, such as SQLCipher-based options. The comparison with other storage is in Local storage.

Also remember:

  • Do not store passwords. Store a token that can be revoked, and let the server decide.
  • Clear everything on sign-out, including cached user data and images.
  • Consider backups: on Android, exclude sensitive files from auto-backup if needed.
  • Never log secrets (logging).
  • Offer biometric unlock (local_auth) for sensitive screens as an extra layer, not as the only protection.

HTTPS everywhere, and certificate pinning

All network traffic must use HTTPS. Both Android and iOS block plain HTTP by default for good reason. TLS stops people on public Wi-Fi from reading or changing requests, as long as the device trusts the right certificate authorities (CAs).

Certificate pinning goes one step further. Normally the device trusts any certificate signed by any of dozens of CAs, including ones an employer, a malware app or a compromised authority might add. Pinning makes the app accept only your server's certificate (or its public key) and reject everything else, so even a certificate that looks valid is refused.

DART
// With dio: compare the server certificate fingerprint to a pinned value.
final dio = Dio();
(dio.httpClientAdapter as IOHttpClientAdapter).createHttpClient = () {
  final client = HttpClient();
  client.badCertificateCallback = (cert, host, port) => false; // never allow bad certs
  return client;
};

dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) {
  // Real code would verify the certificate hash during the TLS handshake,
  // for example with a pinning package or a SecurityContext with your own CA.
  handler.next(options);
}));

The code above only shows where pinning plugs in: dedicated packages and SecurityContext configurations do the actual handshake check. The tradeoffs are real:

  • Pin the public key or an intermediate CA, not just the leaf certificate, so routine certificate renewals do not lock users out.
  • Ship a backup pin and a way to update pins; a wrong pin bricks networking until users update the app.
  • Pinning blocks debugging proxies. Disable it in debug builds so you can inspect your own traffic.
  • It raises the bar against man-in-the-middle attacks. A user who controls their own phone can still bypass it, so it complements server-side checks.
JS Pinning compares a fingerprint, not just validity

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The attacker's certificate is valid from the operating system's point of view, yet pinning rejects it because the key is not one the app expects. Notice the backup pin: when you rotate keys, old app versions keep working.

Authentication and tokens

Use short-lived tokens, not stored passwords.

  1. The user signs in; the server returns a short-lived access token (minutes) and a longer-lived refresh token.
  2. The app sends the access token in an Authorization: Bearer ... header on each request.
  3. When the server answers 401, the app uses the refresh token to get a new access token, and retries once.
  4. On sign-out, the app deletes both tokens and the server revokes the refresh token.

Rules of thumb: keep tokens in secure storage, keep them out of URLs (URLs end up in logs), prefer standard flows such as OAuth 2.0 with PKCE through the system browser (flutter_appauth) over your own login screens for third-party providers, and let Firebase Auth or a similar service handle the hard parts when it fits.

JS Access token expiry and a refresh retry

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Validate input, and never trust the client

Input comes from forms, deep links, QR codes, clipboard, files, push payloads and API responses. Validate early for good user feedback (Forms and validation), and remember that the server must validate again, because anyone can send requests without using your app.

  • Check type, length and format, and prefer allow-lists ("these five values") over block-lists.
  • Parse server JSON defensively: unexpected fields or null values should produce an error, not a crash (HTTP and JSON).
  • Treat deep link parameters as untrusted (go_router): a link such as myapp://reset?token=... or myapp://pay?amount=0 must be checked like any other input.
  • Use parameterized queries with SQLite or drift; never build SQL by joining strings.
  • WebViews: load only trusted URLs, and be careful with JavaScript channels that expose app features.
  • Do not trust client-side decisions such as "is the user premium?" or "is the price 0?". The server owns prices, permissions and entitlements.
JS Allow-list validation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second request fails on three fields, and the extra isAdmin field is reported instead of silently accepted. That "unexpected field" rule is a cheap defense against attempts to smuggle in privileges.

More hardening, briefly

  • Keep dependencies updated and review packages before adding them; run flutter pub outdated regularly. Plugins run with your app's full permissions.
  • Request minimal permissions and explain why (device features).
  • Detect tampering with care: root/jailbreak checks and platform attestation APIs (Play Integrity, App Attest) can help for banking-style apps, but they are signals sent to your server, not guarantees.
  • Screenshots and the app switcher: hide sensitive screens (FLAG_SECURE on Android, a blur overlay on iOS) if they show private data.
  • Disable debug features in release: no debug banners, verbose logs or test endpoints (build flavors separate environments cleanly).
  • Test it: inspect your own release build, check what its traffic and files reveal, and fix surprises.

Security is about reducing risk, not reaching zero. Put the real authority on the server, store only what you must, protect what you store, and assume everything on the device can be read.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You pass an API key with --dart-define. Where can an attacker find it?

    dart-define keeps the key out of source control but it still ends up inside the app, where it can be extracted.
  2. 2. Where should a refresh token be stored on the device?

    Secure storage uses the platform's protected store. Plain preferences and source constants are readable.
  3. 3. What does certificate pinning add on top of normal HTTPS?

    Pinning limits trust to the keys you expect, defeating man-in-the-middle certificates that the device would otherwise accept.
  4. 4. What does --obfuscate do?

    It renames symbols. Strings and assets stay readable, so it never protects secrets.
  5. 5. A form checks that the price is not 0. Is that enough?

    Anyone can send requests without your app, so only server-side checks are security.

Summary

  • The device belongs to the user: never ship true secrets, and put authority (prices, permissions, secret API keys) on the server.
  • --dart-define and obfuscation keep keys out of source and code harder to read, but do not make embedded strings safe.
  • Store tokens in flutter_secure_storage, clear them on sign-out and never log them.
  • Use HTTPS everywhere; add certificate pinning (with backup pins) when the risk justifies it.
  • Use short-lived access tokens with refresh tokens, and standard OAuth with PKCE for third-party sign-in.
  • Validate all input, including deep links and server responses, with allow-lists, and validate again on the server.

Next: Build Flavors, Environments and Config