15 KiB
Gemini Prompt: Implement JWT Authentication with Refresh Token Rotation
Context
I have a partially built Android Kotlin application that needs secure JWT authentication with rotating refresh tokens for persistent login. The authentication service is already built and running at http://localhost:3000. The app should keep users logged in using secure token storage and automatic token refresh.
Authentication Service Details
Base URL: http://localhost:3000 (development)
Authentication Flow:
- User requests OTP via
POST /auth/request-otp - User verifies OTP via
POST /auth/verify-otp→ receivesaccess_tokenandrefresh_token - Access token (15 min expiry) is used for authenticated API calls
- Refresh token (7 days expiry) is used to get new tokens when access token expires
- Refresh tokens rotate on each use (must save new refresh_token)
Key Endpoints:
1. Request OTP
POST /auth/request-otp
Body: { "phone_number": "+919876543210" }
Response: { "ok": true }
2. Verify OTP (Login)
POST /auth/verify-otp
Body: {
"phone_number": "+919876543210",
"code": "123456",
"device_id": "android-installation-id",
"device_info": {
"platform": "android",
"model": "Samsung SM-M326B",
"os_version": "Android 14",
"app_version": "1.0.0",
"language_code": "en-IN",
"timezone": "Asia/Kolkata"
}
}
Response: {
"user": { "id": "...", "phone_number": "...", "name": null, ... },
"access_token": "eyJhbGc...",
"refresh_token": "eyJhbGc...",
"needs_profile": true,
"is_new_device": true,
"is_new_account": false
}
3. Refresh Token (Get New Tokens)
POST /auth/refresh
Body: { "refresh_token": "eyJhbGc..." }
Response: {
"access_token": "eyJhbGc...",
"refresh_token": "eyJhbGc..." // NEW token - MUST save this
}
4. Get User Details (Authenticated)
GET /users/me
Headers: Authorization: Bearer <access_token>
Response: {
"id": "...",
"phone_number": "+919876543210",
"name": "John Doe",
"user_type": "seller",
"last_login_at": "2024-01-20T14:22:00Z",
"location": { ... },
"locations": [ ... ],
"active_devices_count": 2
}
5. Logout
POST /auth/logout
Body: { "refresh_token": "eyJhbGc..." }
Response: { "ok": true }
Implementation Requirements
1. Secure Token Storage
Use EncryptedSharedPreferences (Android Security Library):
- Store
access_tokenandrefresh_tokensecurely - Never use plain SharedPreferences
- Never log tokens in console/logs
- Clear tokens on logout or app uninstall
Implementation:
// Use androidx.security:security-crypto:1.1.0-alpha06
// Store tokens using EncryptedSharedPreferences with MasterKey
2. Token Management
Access Token:
- Lifetime: 15 minutes
- Used in
Authorization: Bearer <token>header for all authenticated requests - Automatically refreshed when expired (401 response)
Refresh Token:
- Lifetime: 7 days (configurable)
- Idle timeout: 3 days (if unused for 3 days, becomes invalid)
- ROTATES on each refresh - always save the new refresh_token
- Stored securely, never sent in URLs or logs
Token Refresh Flow:
1. API call returns 401 (Unauthorized)
2. Get refresh_token from secure storage
3. Call POST /auth/refresh with refresh_token
4. Receive new access_token and new refresh_token
5. Save BOTH new tokens securely
6. Retry original API call with new access_token
7. If refresh fails → clear tokens → redirect to login
3. Auto-Refresh Interceptor/Plugin
Implement automatic token refresh:
- Intercept all API requests
- Add
Authorization: Bearer <access_token>header automatically - On 401 response:
- Refresh token automatically
- Retry original request
- If refresh fails, clear tokens and redirect to login
Use either:
- Ktor: HTTP client interceptor/plugin
- Retrofit: OkHttp interceptor
4. Success Page Implementation
After successful login (OTP verification), show a Success/Home screen that:
-
Fetches User Details:
- Call
GET /users/mewith access_token - Display: name, phone_number, user_type, last_login_at
- Display location if available (city, state, pincode)
- Handle loading and error states
- Call
-
Persistent Login:
- Check for stored tokens on app launch
- If tokens exist and valid → auto-login user
- If tokens expired → attempt refresh
- If refresh fails → show login screen
-
Logout Button:
- Clear all tokens from secure storage
- Call
POST /auth/logoutwith refresh_token - Navigate back to login screen
- Show confirmation dialog before logout
5. Security Requirements
Critical Security Rules:
- ✅ Store tokens only in
EncryptedSharedPreferences - ✅ Never log tokens or sensitive data
- ✅ Always use HTTPS in production (http://localhost only for dev)
- ✅ Implement certificate pinning for production
- ✅ Handle token reuse detection (if refresh returns 401, force re-login)
- ✅ Clear tokens on logout, app uninstall, or security breach
- ✅ Validate device_id consistently (use Android ID or Installation ID)
- ✅ Handle network errors gracefully without exposing tokens
6. Error Handling
Handle these scenarios:
- 401 Unauthorized → Refresh token → Retry
- 401 on refresh → Clear tokens → Redirect to login (session expired)
- Network errors → Show user-friendly message, retry option
- Invalid OTP → Show error, allow retry
- Token expired → Auto-refresh silently (user shouldn't notice)
- Refresh token expired → Show "Session expired, please login again"
7. Device Information
Send device info during login:
- Use Android ID or Firebase Installation ID for
device_id - Collect: platform, model, OS version, app version, language, timezone
- Send in
device_infoobject during OTP verification
Code Structure Requirements
Data Models (Kotlinx Serialization)
@Serializable
data class User(...)
@Serializable
data class VerifyOtpResponse(...)
@Serializable
data class RefreshResponse(...)
// Include all necessary models with @SerialName for snake_case JSON
Token Manager
class TokenManager(context: Context) {
fun saveTokens(accessToken: String, refreshToken: String)
fun getAccessToken(): String?
fun getRefreshToken(): String?
fun clearTokens()
}
API Client with Auto-Refresh
class AuthApiClient {
// Automatically adds Authorization header
// Automatically refreshes token on 401
// Handles token rotation
}
ViewModel Pattern
class SuccessViewModel : ViewModel() {
// Fetch user details
// Handle logout
// Observe authentication state
}
User Experience Flow
-
App Launch:
- Check for stored tokens
- If valid → navigate to Success/Home screen
- If invalid/expired → show Login screen
-
Login Screen:
- Enter phone number → Request OTP
- Enter OTP code → Verify OTP
- On success → Save tokens → Navigate to Success screen
-
Success/Home Screen:
- Show loading indicator
- Fetch user details from
/users/me - Display: Name, Phone, Profile Type, Location, Last Login
- Show logout button
- Handle token refresh silently if needed
-
Logout:
- Show confirmation dialog
- Call logout API
- Clear tokens
- Navigate to Login screen
Dependencies Required
// HTTP Client
implementation("io.ktor:ktor-client-android:2.3.5")
implementation("io.ktor:ktor-client-content-negotiation:2.3.5")
implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.5")
// Secure Storage
implementation("androidx.security:security-crypto:1.1.0-alpha06")
// Serialization
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")
// Coroutines
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
// ViewModel
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.2")
Testing Checklist
- Login with OTP and receive tokens
- Tokens stored securely in EncryptedSharedPreferences
- Success page displays user details from
/users/me - Access token auto-refreshes when expired (wait 15+ min)
- Refresh token rotates correctly (save new token)
- Logout clears tokens and navigates to login
- App remembers login after restart (if tokens valid)
- Session expires gracefully after 3 days idle
- Network errors handled gracefully
- No tokens logged in console/logs
Specific Implementation Notes
-
Phone Number Format:
- Accept user input (can be 10 digits or with +91)
- Server auto-normalizes:
9876543210→+919876543210 - Always send in E.164 format
-
Device ID:
- Use consistent identifier: Android ID or Firebase Installation ID
- Must be 4-128 alphanumeric characters
- Server sanitizes invalid IDs
-
Token Rotation:
- CRITICAL: After refresh, the new
refresh_tokenreplaces the old one - Old refresh_token becomes invalid immediately
- Always save the new refresh_token from refresh response
- CRITICAL: After refresh, the new
-
Base URL Configuration:
- Development:
http://localhost:3000 - Production: Use environment-based configuration
- Consider using BuildConfig for different environments
- Development:
-
API Response Handling:
- All error responses:
{ "error": "message" } - Success responses vary by endpoint
- Always check HTTP status code before parsing JSON
- All error responses:
Security Validation Checklist
Before considering the implementation complete, verify:
- ✅ No tokens in logs/console
- ✅ Tokens only in EncryptedSharedPreferences
- ✅ Automatic token refresh works
- ✅ Token rotation handled correctly
- ✅ Tokens cleared on logout
- ✅ Session expiry handled
- ✅ Network errors don't expose tokens
- ✅ HTTPS for production (when deployed)
Expected Behavior
On Successful Login:
- Save
access_tokenandrefresh_tokensecurely - Navigate to Success/Home screen
- Automatically fetch user details from
/users/me - Display user information
- Show logout button
On App Restart (with valid tokens):
- Check stored tokens
- Validate token (or refresh if expired)
- Auto-navigate to Success/Home screen
- Fetch and display user details
On Token Expiration:
- Next API call returns 401
- Automatically refresh token (silently)
- Retry API call with new token
- User experience uninterrupted
On Refresh Token Expiration:
- Refresh attempt fails with 401
- Clear all tokens
- Show "Session expired" message
- Navigate to login screen
On Logout:
- Show confirmation dialog
- Call logout API
- Clear all tokens from storage
- Navigate to login screen
Reference Documentation
The complete API documentation and data models are available in:
how_to_use_Auth.md(in your Android project)- Full API reference with request/response examples
- All data models with Kotlinx Serialization annotations
Deliverables
Please implement:
- TokenManager - Secure token storage using EncryptedSharedPreferences
- AuthApiClient - API client with automatic token refresh and rotation
- Success/Home Screen - Displays user details from
/users/me - Logout functionality - With confirmation and proper cleanup
- Auto-login on app launch - Check tokens and auto-login if valid
- Error handling - Graceful handling of all error scenarios
- Loading states - Show loading indicators during API calls
Code Quality:
- Use Kotlin best practices
- Follow MVVM architecture pattern
- Use Kotlin Coroutines for async operations
- Proper error handling with Result type
- Clean, maintainable, and secure code
Security:
- All tokens encrypted at rest
- No tokens in logs
- Proper token rotation
- Secure network communication
This implementation should provide a secure, production-ready authentication system with persistent login capability. The user should be able to login once and remain logged in (until tokens expire or logout) with seamless token refresh happening automatically in the background.
Gemini Prompt: JWT Auth with Refresh Token Rotation - Copy This to Gemini
I need you to implement secure JWT authentication with rotating refresh tokens in my Android Kotlin app for persistent login. The auth service runs at http://localhost:3000.
API Endpoints
Base URL: http://localhost:3000
- Request OTP:
POST /auth/request-otp→ Body:{ "phone_number": "+919876543210" } - Verify OTP:
POST /auth/verify-otp→ Returns:{ "access_token", "refresh_token", "user", ... } - Refresh Token:
POST /auth/refresh→ Body:{ "refresh_token": "..." }→ Returns new access_token AND new refresh_token (ROTATES) - Get User:
GET /users/me→ Header:Authorization: Bearer <access_token>→ Returns user details with location - Logout:
POST /auth/logout→ Body:{ "refresh_token": "..." }
Critical Requirements
Token Storage (SECURITY):
- ✅ Use
EncryptedSharedPreferences(androidx.security:security-crypto) - ❌ NEVER use plain SharedPreferences
- ❌ NEVER log tokens in console/logs
- ✅ Clear tokens on logout
Token Management:
- Access token: 15 min lifetime, used in
Authorization: Bearer <token>header - Refresh token: 7 days lifetime, rotates on each refresh (SAVE NEW TOKEN)
- Auto-refresh on 401: Get new tokens, retry request, if refresh fails → logout
Success/Home Screen:
- After login → Navigate to Success screen
- Fetch user details from
GET /users/mewith access_token - Display: name, phone_number, user_type, last_login_at, location
- Show logout button with confirmation
- Handle loading/error states
Persistent Login:
- On app launch: Check stored tokens → If valid, auto-login to Success screen
- If tokens expired: Try refresh → If fails, show login screen
- User should stay logged in until logout or 7 days of inactivity
Implementation Tasks
- TokenManager - Secure storage using EncryptedSharedPreferences
- AuthApiClient - With auto-refresh interceptor (handles 401, refreshes, retries)
- Success/Home Activity/Fragment - Displays user details from
/users/me - Logout - Calls logout API, clears tokens, navigates to login
- Auto-login - Check tokens on app launch
Code Requirements
- Use Kotlinx Serialization for JSON
- Use Ktor or Retrofit for HTTP client
- Use MVVM architecture
- Use Kotlin Coroutines
- Handle all errors gracefully
- Show loading indicators
Security Checklist
- ✅ Tokens only in EncryptedSharedPreferences
- ✅ Auto-refresh on token expiration
- ✅ Token rotation handled (save new refresh_token)
- ✅ No tokens in logs
- ✅ Clear tokens on logout
Dependencies
implementation("io.ktor:ktor-client-android:2.3.5")
implementation("io.ktor:ktor-client-content-negotiation:2.3.5")
implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.5")
implementation("androidx.security:security-crypto:1.1.0-alpha06")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")
IMPORTANT: Refresh tokens ROTATE - always save the new refresh_token from refresh response. Reference: See how_to_use_Auth.md in the project for complete API documentation.