Implement a Secure User Authentication Flow in Android
Instruction: Design and describe a secure user authentication flow for an Android application, ensuring the protection of sensitive user data.
Updated
Official answer
Use an established identity provider and maintained integration library. For federated sign-in, OpenID Connect supplies authentication on top of OAuth 2.0; OAuth access delegation alone is not proof of the user's identity. Offer clear cancellation, recovery and signed-out states.
For a browser-based native-app flow, use authorization code with PKCE through an external user agent such as a browser/custom tab. Generate an unpredictable verifier, send its S256 challenge, and bind the callback to the outstanding request with state and the appropriate OIDC nonce checks. Register and validate the exact redirect URI; prefer verified app links where supported. A native app is a public client: a secret embedded in its package is not confidential. Avoid embedded credential-entry WebViews and implicit-token flows.
Let the integration validate issuer, audience, signature, expiry and required OIDC response claims. Exchange the code with the verifier over validated HTTPS. The API validates its access token and authorization independently; do not use an ID token as an arbitrary API access token.
Keep access tokens short-lived according to provider policy, minimize persistence and protect stored refresh credentials with appropriate app-private encryption/key handling. Keystore stores keys, not arbitrary bearer-token records, and cannot make a compromised authorized process unable to use them. Use supported refresh rotation or sender constraints, handle refresh failure by returning to sign-in, and revoke/clear the intended session on logout.
A local biometric prompt can gate a device action or key; it does not by itself authenticate an account to the server or establish MFA there. Test cancelled/wrong callbacks, expired tokens, concurrent refresh, account switching and recovery without logging secrets.
Native-app authorization, OAuth security practices, OpenID Connect validation, Keystore boundaries