Protecting API keys

Security Mid-level Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Pick the fix

The app calls a paid AI API with a secret key. Where should the key live?

Options
Hint 1 of 1

Can a key in the app ever be secret?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A On your backend, which the app calls and which adds the key

Correct. The key never ships, and you control access and quotas.

Why not the others?
  • B In the binary, obfuscated. Obfuscated strings can still be extracted at runtime.
  • C In the Keychain, written on first launch. The key must ship in the app to be written, so it can be extracted.
  • D In Info.plist. Anyone can read it from the app bundle.

30-second answer

Assume anything shipped in the app can be extracted, whether it is in code, plists or obfuscated. Keep real secrets on your server and have the app call your backend, which adds the key. For keys that must ship, such as public SDK keys, restrict them with the provider (bundle ID, quotas, scopes) and protect your own endpoints with authentication and App Attest.

Practise saying it · 30 s. No recording, just a timer

Explain how you protect API keys.

Say your answer out loud, then check which of these points you covered:

  • Shipped means extractable
  • Backend proxy
  • Restrict public keys

Deep dive

Don't commit keys to git; inject them at build time with xcconfig files kept out of the repo.

Build-time injection keeps keys out of source, not out of the binary.

Rotate keys that leak, and monitor usage.

Short-lived tokens from your backend limit the damage of a leak.

Common mistakes

  • Believing obfuscation makes a key secret.
  • Shipping a key with full account permissions.

Senior take & follow-ups

Seniors explain that a shipped secret isn't a secret, and design around it.

Follow-up questions

Think of your answer first, then open the hint.

  1. Is xcconfig injection secure?

    Show hint

    It keeps keys out of git, but they're still in the binary.

  2. How do you call a paid API safely?

    Show hint

    Through your backend, which holds the key.

Suggest a fix if something here is wrong or out of date.