Prompt
How do I handle user login and identity management in a mobile backend?
Latest observation
A solid mobile backend should treat login and identity management as separate concerns:
- Authentication: “Who are you?”
- Authorization: “What are you allowed to do?”
- Identity management: “How do we create, link, update, and revoke user accounts safely over time?”
Here’s a practical approach.
1. Use a standard identity protocol
For most mobile apps, the best choice is:
- OAuth 2.0 / OpenID Connect (OIDC) for sign-in
- Use an identity provider (IdP) like:
- Auth0
- Firebase Authentication
- Amazon Cognito
- Okta
- Azure AD B2C / Entra External ID
- Keycloak (self-hosted)
Avoid building your own password system unless you have a strong reason.
2. Recommended login flow for mobile
For mobile apps, use the Authorization Code Flow with PKCE:
- User taps “Sign in”
- App opens the system browser or secure auth session
- User authenticates with the IdP
- App receives an authorization code
- App exchanges code for tokens using PKCE
- Backend/API validates tokens on every request
Why this matters:
- No client secret is stored in the app
- Safer than older implicit flows
- Works well with social login and enterprise SSO
3. Token strategy
Usually you’ll deal with:
- Access token: short-lived, used to call APIs
- Refresh token: longer-lived, used to get new access tokens
- ID token: contains identity claims, mainly for the client app
Best practices:
- Keep access tokens short-lived (e.g. 5–15 min)
- Store refresh tokens securely
- Rotate refresh tokens when possible
- Support token revocation/logout
4. Secure storage on mobile
Never store credentials in plain storage.
Use:
- iOS: Keychain
- Android: Keystore / EncryptedSharedPreferences
- Cross-platform secure storage libraries that wrap these
Store:
- Refresh token
- Minimal user profile cache if needed
Don’t store:
- Passwords
- Secrets
- Long-lived API keys
5. Backend identity model
In your backend, keep your own user record even if auth is handled by an IdP.
Typical user table:
user_idinternal UUIDauth_provider(google, apple, email, enterprise-saml, etc.)provider_subject(stable unique ID from IdP)emailnamestatus(active, suspended, deleted)- timestamps
This lets your backend remain independent of any one provider.
6. Link identity to your app user
When a user logs in:
- Validate the token from the IdP
- Extract stable identity claims like:
subissemail(if trustworthy and verified)
- Look up the user by
(issuer, subject) - If not found, create a new internal user profile
This is better than using email alone, because email can change.
7. Support account linking
Users may sign in with:
- Apple
- Email/password
- Enterprise SSO
You may want one app account linked to multiple identities.
Approach:
- Create a primary internal user
- Add a separate table for linked identities
- Require proof of control before linking a second identity
- Be careful to prevent account takeover via email collision
8. Registration and profile onboarding
Authentication tells you who they are; registration/onboarding fills in app-specific data.
Typical flow:
- First login succeeds
- Backend creates a user row
- App asks for missing profile data:
- username
- preferences
- consent
- age verification, if needed
Keep auth and profile separate.
9. Session handling and logout
For mobile, “logout” should mean:
- Clear local tokens
- Revoke refresh token server-side if supported
- Remove local cached user data as appropriate
Remember:
- Access tokens often expire naturally
- Refresh token revocation is what really ends the session
10. Authorization
After login, decide what the user can do using:
- Roles:
user,admin,support - Permissions/scopes:
read:profile,write:order - Resource ownership checks: “Can this user edit this record?”
Don’t rely only on frontend checks.
11. Account recovery and security
If you manage password login yourself:
- Hash passwords with Argon2id or bcrypt
- Add rate limiting
- Use MFA
- Implement secure password reset with one-time expiring tokens
If you use an IdP, let it handle these flows where possible.
12. Protect your API
Your backend should:
- Verify JWT signatures
- Check issuer, audience, expiry
- Validate scopes/roles
- Reject expired or revoked tokens
- Use HTTPS everywhere
For sensitive apps, also consider:
- Device binding
- Certificate pinning
- Risk-based authentication
- Step-up MFA for critical actions
13. Good mobile UX patterns
- Use “Sign in with Apple” where required/appropriate
- Offer passwordless options if possible
- Keep the login screen simple
- Preserve session across app restarts
- Handle token refresh transparently
- Avoid forcing re-login too often
14. Common mistakes
- Storing passwords in the app
- Using email as the only identity key
- Putting long-lived secrets in the client
- Accepting tokens without signature validation
- Building custom auth instead of using OIDC/OAuth
- Mixing profile data and authentication data
- Not planning for account linking or migration
15. Simple architecture
A common setup looks like this:
- Mobile app
- Starts OIDC login
- Stores refresh token securely
- Identity provider
- Handles login, MFA, social login, recovery
- API backend
- Verifies JWT access tokens
- Maps
subto internal user record - Enforces authorization
- Database
- Stores app profile, permissions, linked identities
If you want, I can also give you:
- a sample architecture diagram,
- a JWT validation example, or
- a step-by-step login flow for iOS/Android.