Authentication is one of the few parts of a mobile app where "works" and "correct" can be very far apart. Sign-in through a WebView that can read the password, a refresh token living forever in SharedPreferences, several parallel token refreshes that end up signing the user out: all of these "work" until the first security audit or the first incident.
This article is a practical walkthrough of OAuth 2.0 with PKCE for native apps: what the flow looks like, why WebViews are off the table, how to choose token lifetimes, how to refresh without race conditions and what to do on sign-out. It is grounded in current IETF standards, primarily RFC 8252 and RFC 9700.
Why a mobile app is a "public client"
In classic OAuth a server-side application holds a client secret stored on the server. A mobile app cannot keep a secret: any string in the build can be extracted by decompilation in minutes. So the specification classifies native apps as public clients, and RFC 8252 (OAuth 2.0 for Native Apps) requires two things: use an external user agent (the system browser) and protect the code exchange with PKCE.
The takeaway for the team is simple: no client secret in the mobile build. If a provider insists on one, the code-for-token exchange must happen through your backend.
Authorization Code + PKCE, step by step
- The app generates a code_verifier, a random 43–128-character string, and computes code_challenge = BASE64URL(SHA-256(code_verifier)), as described in RFC 7636. Avoid the plain method.
- It opens the authorisation page in the system browser with client_id, redirect_uri, scope, state, code_challenge and code_challenge_method=S256.
- The user signs in on the provider's page: password, passkey, 2FA, Google or Apple sign-in. The app never sees these details.
- The provider redirects to redirect_uri with a one-time authorisation code and the state. The app checks that the state matches what it sent.
- The app exchanges the code for tokens, including the original code_verifier. The server checks that its hash matches the code_challenge.
- The app receives an access token, a refresh token and, with OpenID Connect, an ID token, and stores them in secure storage.
PKCE solves a specific problem: if a malicious app intercepts the redirect carrying the code (for example by registering the same custom URL scheme), it cannot redeem the code without the code_verifier, which never left your app's memory.
System browser, not a WebView
An embedded WebView gives the app full control over the sign-in page: it can read the typed password and the cookies. That is why RFC 8252 explicitly rules it out for authorisation, and since 2021 Google has blocked Google sign-in in embedded WebViews. The right tools:
| Platform | Tool | What you get |
|---|---|---|
| iOS | ASWebAuthenticationSession | A system browser sheet, optional Safari cookie sharing, return via callback |
| Android | Custom Tabs | A browser tab over the app, with the browser's password manager and passkeys |
| Both | AppAuth libraries | A ready-made flow implementation, PKCE, redirect handling |
On iOS that is ASWebAuthenticationSession, on Android Custom Tabs, and the open-source AppAuth libraries implement the whole flow on both platforms. A bonus for users: password managers and saved sessions work, so sign-in gets faster.
Redirect URI
The safest option is a domain-verified HTTPS link: Universal Links on iOS and App Links on Android. RFC 8252 permits a custom scheme (com.example.app:/callback), but another app can register it too, which is exactly why PKCE is mandatory. Use a reverse-domain scheme rather than something short like myapp://.
Access and refresh tokens: lifetime and rotation
The access token is short-lived and sent with every API request. The refresh token lives longer and is used only to obtain new access tokens. Exact values depend on the product's risk profile; these are the guidelines we use:
| Product type | Access token | Refresh token | Extra measures |
|---|---|---|---|
| Content, media, social | 15–60 min | 30–90 days, sliding | Refresh token rotation |
| E-commerce, delivery | 10–30 min | 30–60 days | Re-authentication to change payment details |
| Finance, health | 5–15 min | Hours to days, absolute session cap | Biometrics for sensitive actions, device binding |
RFC 9700 (OAuth 2.0 Security Best Current Practice) recommends that public clients either bind refresh tokens to a client key (for example with DPoP) or use rotation: every refresh issues a new refresh token and invalidates the old one. If the server sees an already invalidated token being reused, that signals theft and the whole token family should be revoked.
Refreshing without race conditions
A typical bug we find in audits: on returning from the background the app fires five requests at once, all get 401, and all five refresh the token in parallel. With rotation, the first gets a new refresh token, the other four present the invalidated one, the server detects "reuse" and signs the user out.
The correct pattern
- All requests go through one HTTP client with an interceptor (OkHttp Authenticator on Android, a wrapper around URLSession on iOS).
- On 401 the interceptor checks whether a refresh is already in progress. If so, it waits for that result instead of starting another (mutex, actor or single-flight).
- After a successful refresh, all queued requests are retried with the new access token. Each request is retried at most once.
- If the refresh fails with invalid_grant, clear the tokens and send the user to sign-in while preserving context (where they were heading).
- Do not confuse a network error during refresh with invalid_grant: never sign a user out just because they are offline.
A useful optimisation is proactive refresh: if the access token expires in under a minute, refresh it before the request rather than after a 401.
Storing tokens
Tokens are secrets and must be stored accordingly: Keychain on iOS, Android Keystore (for example, a key that encrypts the storage) on Android. Never UserDefaults, plain SharedPreferences, logs, analytics or crash reports. Make sure the debug HTTP logger does not ship in release builds and does not print the Authorization header. We will cover storage in depth in a separate article on Keychain and Keystore. Baseline authentication and storage requirements are collected in OWASP MASVS (the MASVS-AUTH and MASVS-STORAGE groups).
Sign-out and revocation
- Revoke the refresh token on the server via the revocation endpoint (RFC 7009), not just delete it from the device.
- Clear local data: caches, database, user files, the push token on the backend.
- End the browser session if SSO is used; otherwise the next sign-in silently reuses the same account, which surprises users on shared devices.
- Let users end other sessions from settings: a device list and a "Sign out everywhere" button.
- After a password change, revoke every refresh token except the current one.
Common mistakes
- Sign-in in a WebView, or a native form sending the password straight to the OAuth server (Resource Owner Password Credentials, a grant RFC 9700 says must not be used).
- The implicit flow with a token in the URL fragment: deprecated and not recommended.
- A client secret in app code or a build configuration file.
- No state check, or PKCE with the plain method.
- A non-expiring refresh token without rotation.
- Parallel token refreshes that sign the user out.
- Signing out on any network error during refresh.
Implementation checklist
- Authorization Code + PKCE (S256), state validation.
- System browser: ASWebAuthenticationSession / Custom Tabs, or AppAuth.
- Redirect via Universal Links / App Links or a reverse-domain scheme.
- No secrets in the build; confidential exchanges go through the backend.
- Short-lived access tokens, refresh token rotation with reuse detection.
- Single-flight refresh in the network layer, one retry per request.
- Tokens only in Keychain / Keystore, never in logs or analytics.
- Server-side revocation on sign-out, "sign out everywhere", revocation after a password change.
- Tests: expired token, parallel 401s, sign-out while offline, returning from the background after a week.
Sources: RFC 8252: OAuth 2.0 for Native Apps; RFC 7636: PKCE; RFC 9700: OAuth 2.0 Security Best Current Practice; RFC 7009: Token Revocation; RFC 9449: DPoP; Apple: ASWebAuthenticationSession; Chrome Custom Tabs; AppAuth; Google: OAuth in embedded WebViews; OWASP MASVS.



