Access tokens are short-lived on purpose, so the client renews them with a refresh token instead of asking the user to log in again. The standard approach — refresh tokens 1. At login, the server returns an access token (for example 15 minutes) and a refresh token (for example 7–30 days). 2. When the access token expires (the API returns 401), or shortly before it expires, the client calls the token endpoint: POST /token grant_type=refresh_token&refresh_token=<token>&client_id=<id> 3. The server validates the refresh token (exists, not expired, not revoked, belongs to this client), issues a new access token and — with rotation — a new refresh token, invalidating the old one. 4. The client retries the failed request with the new access token. Implementing your own refresh endpoint (if you issue tokens yourself) - Generate refresh tokens as long random values (RandomNumberGenerator.GetBytes(64)) and store a hash in the database with user ID, expiry, device information and a "replaced by" field. - Rotation and reuse detection: if an already-used refresh token is presented again, assume theft and revoke the whole token family. - Revoke refresh tokens on logout, password change or admin action. - Re-check that the user is still active and their roles are current when issuing new access tokens. Client-side handling - An HTTP interceptor catches 401, calls refresh once, queues concurrent requests while the refresh is in flight (to avoid several simultaneous refreshes), then replays them. - If refresh fails, clear the session and redirect to login. - In SPAs, libraries such as MSAL do this automatically (silent token acquisition). Storage - Browser: avoid localStorage for refresh tokens; prefer a BFF with HttpOnly, Secure, SameSite cookies, or in-memory tokens with rotation. - Mobile: Keychain or Keystore. Alternatives - Sliding sessions with cookie authentication, where the server extends the session on activity. - Silent re-authentication against the identity provider's session (hidden iframe or redirect), now limited by third-party cookie restrictions, which is why refresh tokens with rotation are preferred.
Ravindra Wadile · · 0 likes