Building Secure API Communication on Android
TLS configuration, certificate pinning without self-inflicted outages, request integrity, attestation tokens and why secrets never belong in the APK.
- #certificate pinning
- #tls
- #okhttp
- #api security
- #network security config
Table of contents
Your API is the real product; the app is one of its clients. Securing the channel between them means protecting confidentiality, making sure the client is genuine, and making tampered requests useless.
Baseline: TLS everywhere
Android blocks cleartext traffic by default for modern target SDKs. Make it explicit with a Network Security Config:
<network-security-config>
<base-config cleartextTrafficPermitted="false">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>Certificate pinning — carefully
Pinning restricts which certificates your app accepts for your domains, so a proxy with a user-installed CA can't read traffic.
val pinner = CertificatePinner.Builder()
.add(
"api.example.com",
"sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", // current key
"sha256/BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=", // backup key
)
.build()
val client = OkHttpClient.Builder()
.certificatePinner(pinner)
.build()Make requests tamper-evident
TLS protects the pipe, not the endpoints. A hooked client can still send forged requests over a perfectly valid TLS connection. Add:
- Short-lived tokens rather than long-lived API keys.
- Nonces and timestamps to prevent replay.
- Server-side validation of every business rule — never trust client-computed amounts or permissions.
{
"nonce": "b2f4c1e0-8a51-4c1a-9d1e-6a3f7e1d2c90",
"timestamp": 1760000000,
"payload": { "action": "transfer", "amount": "1500.00" },
"integrityToken": "<opaque token verified by the backend>"
}Prove the client is genuine
App and device attestation (for example the Play Integrity API) lets the backend verify that a request comes from an unmodified app on a genuine device. The verdict is checked server-side; the app only relays the token.
No secrets in the APK
Anything shipped in the app — strings, resources, native libraries — can be extracted. Treat embedded keys as public. If the server needs to trust a client, use attestation and per-session credentials instead.
Checklist
- Cleartext disabled via Network Security Config
- SPKI pinning with backup pins and a rotation plan
- Short-lived, scoped tokens
- Replay protection on sensitive endpoints
- Attestation verified server-side
- No long-lived secrets in the client