Appearance
Refresh Token Flow
This page documents the token refresh flow in GrydAuth, which allows users to obtain new access tokens without re-entering their credentials.
v5 (Epic 533) — refresh token in an HttpOnly cookie. The refresh token is no longer returned in the JSON body. It is delivered exclusively in a
Set-Cookie: __Secure-gryd.refresh; HttpOnly; Secure; SameSite; Path=/api/v1/authcookie (inaccessible to JavaScript).POST /api/v1/auth/refreshreads the token from that cookie — the request body carries only an optionaltenantId, which must be the session's own tenant (see 2.5). Because the endpoint is now cookie-authenticated it requires the CSRF headerX-Gryd-Csrfmatching the readablegryd.csrfcookie (double-submit), and the SPA must sendcredentials: include. A missing refresh cookie →401; a missing/mismatched CSRF header →403. The single-use rotation rewrites the cookie on every refresh, and/logoutexpires it. Seetoken-storage-backend-change-inventory.md.
Overview
Access tokens in GrydAuth v5 are short-lived by design — capped at 15 minutes, default 10 — because their roles/permissions are a snapshot at issuance time. When an access token expires, the client can use the refresh token to obtain a new access token without requiring the user to log in again.
Token Lifetimes
| Token Type | Default Lifetime | Configurable? | Purpose |
|---|---|---|---|
| Access Token | 10 minutes | Yes — JwtSettings:ExpirationMinutes, validated at boot, must be 1–15 | API authentication |
| Refresh Token ("keep me signed in" on, or not said) | 7 days | Yes — JwtSettings:RefreshTokenLifetimeMinutes (≥ 60) | Obtain new access tokens |
| Refresh Token ("keep me signed in" off) | 12 hours | Yes — JwtSettings:SessionRefreshTokenLifetimeMinutes (60 up to the persistent one) | Same, with session cookies |
| Global Token | 2 minutes | Yes — JwtSettings:GlobalTokenExpirationMinutes, 1–15 | Tenant selection / first login only, see Switch Tenant |
An organization's own refresh lifetime (login policy, US-OS.0.6) takes precedence over the persistent default; the "keep me signed in" off lifetime is a cap on top of it. The frontend contract — cookies, the rememberMe flag, the 401 codes — is in session-lifetime-contract.md (US-Q.0.4).
Sequence Diagram
100% 💡 Use Ctrl + Scroll para zoom | Arraste para navegar
Step-by-Step Explanation
Phase 1: Access Token Expiration
When the access token expires, API requests return 401 Unauthorized with a ProblemDetails body carrying code: "TOKEN_EXPIRED". The client should detect this and initiate the refresh flow. See the canonical error code matrix.
Phase 2: Token Refresh
2.1 Send Refresh Request
http
POST /api/v1/auth/refresh
Cookie: __Secure-gryd.refresh=<httponly>; gryd.csrf=<value>
X-Gryd-Csrf: <value>
Content-Type: application/json
{
"tenantId": "550e8400-e29b-41d4-a716-446655440000"
}tenantId is optional and is an assertion, not a choice (DEC-BUG-1727). The refresh is authenticated by the cookie, never by the Bearer — which is usually expired by now — so the session's tenant is the refresh token's. Omitted or equal to it, the session renews; any other tenant answers 409 SESSION_TENANT_CONFLICT before rotation, so the cookie stays usable and a refresh with an empty body re-reads the session. A refresh never moves the session to another tenant: that is Switch Tenant, with the target's MFA gate, session ceiling and Zero Trust checks.
The response is the same AuthenticationResult shape as Login — the token field is token, not accessToken, and current roles/permissions/tenant info are included, not just a bare token pair.
2.2 Validate Refresh Token
The refresh token is validated against Redis cache:
csharp
var tokenData = await _cache.GetAsync<RefreshTokenData>(refreshToken);
if (tokenData == null)
return Result.Failure("Invalid refresh token");2.3 Validate User Status
The system ensures:
- User still exists
- User is active (
IsActive = true) - User is not locked out
2.4 Token Version Check
Token version prevents use of old tokens after:
- Password change
- Admin-forced logout
- Security incident response
csharp
if (tokenData.TokenVersion != user.TokenVersion)
{
await _cache.DeleteAsync(refreshToken);
return Result.Failure("Token invalidated");
}2.5 Tenant Validation
Ensures the user may still act in the session's tenant — an active link to an active tenant, the same rule switch-tenant applies (IUserTenantAccessResolver). A link revoked or a company deactivated mid-session ends the session: 401 SESSION_INVALIDATED, before rotation and without minting anything. (Before DEC-BUG-1727 the refresh fell back to a standard token with no tenant claims.)
Roles and permissions are loaded for that same tenant, so the token can never name one tenant and carry another's grants.
The new tenant token carries the same tenant claims login and switch-tenant write (domain, group_id, group_name), read from the database at refresh time — never copied from the token being refreshed. A company moved to another group carries the new group from this refresh on; one detached from its group carries none. A federated session keeps its anchor claims as well.
2.6 Refresh Roles & Permissions
Important: The new access token contains the current roles and permissions, not the cached ones. This ensures permission changes take effect immediately.
2.7 Token Rotation
For security, GrydAuth implements refresh token rotation:
- Old refresh token is deleted
- New refresh token is generated
- Client must use new refresh token for next refresh
This limits the damage if a refresh token is compromised.
Phase 3: Resume Operations
Client stores the new tokens and continues making API requests.
Automatic Token Refresh
Client-Side Implementation
typescript
// Axios interceptor for automatic refresh
axios.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config;
if (error.response?.status === 401 &&
error.response?.data?.code === 'TOKEN_EXPIRED' &&
!originalRequest._retry) {
originalRequest._retry = true;
try {
const { token, refreshToken } = await authService.refresh();
authStore.setTokens(token, refreshToken);
originalRequest.headers.Authorization = `Bearer ${token}`;
return axios(originalRequest);
} catch (refreshError) {
// Refresh failed - redirect to login
authStore.clearTokens();
router.push('/login');
return Promise.reject(refreshError);
}
}
return Promise.reject(error);
}
);Token Refresh Service
typescript
class AuthService {
private refreshPromise: Promise<AuthenticationResult> | null = null;
async refresh(): Promise<AuthenticationResult> {
// Prevent multiple simultaneous refresh requests
if (this.refreshPromise) {
return this.refreshPromise;
}
this.refreshPromise = this.doRefresh();
try {
return await this.refreshPromise;
} finally {
this.refreshPromise = null;
}
}
private async doRefresh(): Promise<AuthenticationResult> {
const refreshToken = authStore.getRefreshToken();
const response = await api.post('/auth/refresh', { refreshToken });
return response.data;
}
}Sliding Expiration (Rotation Side-Effect, Not a Toggle)
There is no EnableSlidingExpiration setting. The sliding behavior below falls out naturally from rotation: every successful refresh issues a brand-new refresh token with a fresh 7-day expiry (the old one is deleted immediately). As long as the user keeps refreshing within 7 days, the session effectively never expires:
100% 💡 Use Ctrl + Scroll para zoom | Arraste para navegar
Error Scenarios
| Error | HTTP Status | Cause | Client Action |
|---|---|---|---|
| Invalid refresh token | 401 | Token not found in cache | Redirect to login |
| Token expired | 401 | Refresh token TTL exceeded | Redirect to login |
| Token revoked | 401 | Password changed or admin action | Redirect to login |
| User inactive | 401 | Account deactivated | Show account disabled message |
| Tenant access revoked | 401 SESSION_INVALIDATED | Link to the session's tenant removed, or the tenant deactivated | Redirect to login |
| Tenant conflict | 409 SESSION_TENANT_CONFLICT | Body tenantId is not the session's (another tab switched tenant) | Refresh again with an empty body and adopt currentTenant |
| Reuse detection unavailable | 401 | Cache/Redis outage — rotation denied (fail-secure, v5) | Redirect to login |
| Rate limit exceeded | 429 | Too many refresh attempts | Back off, honor Retry-After |
Security Considerations
Refresh Token Storage
| Platform | Recommended Storage |
|---|---|
| Web (SPA) | HttpOnly cookie or memory |
| Mobile | Secure storage (Keychain/Keystore) |
| Desktop | OS credential manager |
Never Store in localStorage
Refresh tokens should never be stored in localStorage due to XSS vulnerability.
Token Rotation Benefits
- Limits exposure window - Stolen tokens become invalid after one use
- Detects theft - If legitimate user's refresh fails, theft is detected
- Audit trail - Each rotation is logged for security analysis
Reuse-Tolerance Window (concurrent renewals)
A browser renews with the same cookie twice without any theft — two tabs, or a burst of parallel 401s each triggering a refresh. Before US-Q.0.4 the race had a winner whose fresh tokens were born revoked, signing the user out. The rotation that wins now opens a window of JwtSettings:RefreshReuseGraceSeconds (30 s by default, 0–120, 0 disables) and records its successor there (protected by ISecretProtector, in the cache). A presentation of the rotated token from the same User-Agent inside the window gets that same successor and a fresh access token, without revoking anything. Outside the window, or from another User-Agent, reuse is theft and revokes the token family as before.
Degraded Mode (Fail-Secure)
Single-use rotation depends on the reuse-detection store (Redis). If that store is unavailable, GrydAuth v5 denies rotation by default and forces re-authentication, rather than issuing a long-lived refresh token without anti-reuse protection (as v4 did under load). The policy is pluggable via IDegradedModeRefreshPolicy (default DenyAllDegradedModeRefreshPolicy); any alternative that issues a token in degraded mode must require MFA step-up, use a very short TTL, and stay behind a feature flag that is off by default. Denials are logged as security events. See the v4 → v5 migration guide.
Absolute Expiration
Recommended, not currently implemented
There is no enforced absolute maximum lifetime today — a user who refreshes regularly can stay signed in indefinitely on the rolling 7-day window above. An AbsoluteExpiration cap is a sensible hardening candidate, but don't document it as existing behavior; verify against StatelessRefreshTokenService before relying on it.
Configuration
jsonc
{
"JwtSettings": {
"ExpirationMinutes": 10, // access-token TTL; 1-15
"GlobalTokenExpirationMinutes": 2, // tenant-selection token; 1-15
"RefreshTokenLifetimeMinutes": 10080, // refresh, "keep me signed in" on (7 days); >= 60
"SessionRefreshTokenLifetimeMinutes": 720, // refresh, "keep me signed in" off (12 h)
"RefreshReuseGraceSeconds": 30 // reuse-tolerance window; 0-120, 0 disables
}
}All keys are validated at boot (JwtSettingsValidator). Access tokens are deliberately short-lived (maximum 15 minutes, default 10) because their authorization claims are snapshots. Refresh-token rotation preserves session continuity, while the shorter access-token TTL bounds exposure to stale claims.
Related Flows
- Login Flow - Initial authentication
- Logout Flow - Token invalidation
- Switch Tenant - Changing tenant context