Split identity from device state A Flutter app calling a Laravel API needs to authenticate the user, store credentials safely, and recover when a token exp...
Split identity from device state
A Flutter app calling a Laravel API needs to authenticate the user, store credentials safely, and recover when a token expires or the device goes offline. Treat the mobile client as an untrusted application: it can hold a token, but it cannot keep a server secret. The API must authorize every protected request.
Choose a token design that fits the threat model. Laravel Sanctum can issue personal access tokens for mobile clients, while an external identity provider may supply short lived access tokens and refresh tokens. Document expiration, rotation, revocation, and device logout before writing the login screen.
Design the login exchange
Use HTTPS for every credential request. Validate input server side, rate limit repeated attempts, and return a consistent error that does not reveal whether a username exists. After authentication, return the token and only the profile fields the app needs. Avoid embedding authorization decisions in the UI alone; the API checks permissions on every resource.
Store tokens using the platform's secure storage mechanism, not plain shared preferences or logs. A token should be removed on logout and revoked on the server when the product requires immediate invalidation.
Handle expiry and concurrency
Centralize API calls in one client layer. When an access token expires, avoid launching a separate refresh call for every simultaneous request. Serialize refresh, retry eligible requests once, and return the user to login if refresh fails. Never retry an unsafe payment or create request without an idempotency key.
On a shared device, clear cached private data on logout. Offline screens should not display another user's data after the account changes.
Test the full lifecycle
Test a valid login, invalid password, revoked token, expired token during concurrent requests, device logout, network loss, and a user removed from a tenant. Verify a copied token cannot access resources outside its server side permissions.
Also confirm that an API error never includes the token in an exception message or analytics payload. Review device backup behavior for the chosen secure storage package so a restored app does not unexpectedly inherit an old session.
Conclusion
Mobile authentication is a lifecycle of issuing, storing, refreshing, authorizing, and revoking credentials. The app handles user experience; the API remains the authority. See mobile app development for the broader integration.
References