-
Notifications
You must be signed in to change notification settings - Fork 0
INACTIVITY_BASED_TOKEN_EXPIRATION
This document describes the implementation of inactivity-based token expiration for NDF Studio. Instead of using a fixed time-based expiration, tokens now expire based on user activity, providing a better user experience while maintaining security.
Previously, JWT tokens had a fixed expiration time (1 hour), which meant that:
- Users working actively would be logged out after 1 hour regardless of their activity
- Users who were inactive for a short time would still have valid tokens
- This created a poor user experience for active users
The new system implements inactivity-based token expiration where:
- Tokens expire if the user has been inactive for more than 20 minutes
- Active users can continue working without interruption
- Inactive users are automatically logged out for security
- The system tracks user activity through API calls and logs
- Extends FastAPI Users' JWT strategy
- Checks user activity from logs during token validation
- Rejects tokens if user has been inactive for too long
- Configurable inactivity threshold (default: 20 minutes)
- Logs all authenticated API requests
- Tracks user activity for inactivity detection
- Excludes certain paths from activity tracking (docs, logs, etc.)
- Provides detailed activity logs with timestamps
- Uses the new
InactivityJWTStrategyinstead of standard JWT strategy - Provides configuration endpoint for frontend
- Configurable inactivity threshold and token lifetime
- Better error handling for inactivity-based expiration
- Fetches configuration from server
- Provides inactivity-specific error messages
- Activity checking utilities
- Shows inactivity warnings
- Displays last activity timestamp
- Provides refresh functionality
- Different UI for inactivity vs. time-based expiration
The inactivity threshold is configured in backend/routes/users.py:
def get_jwt_strategy() -> InactivityJWTStrategy:
return InactivityJWTStrategy(
secret=SECRET,
lifetime_seconds=3600, # 1 hour max lifetime
inactivity_threshold_minutes=20 # 20 minutes inactivity threshold
)The frontend fetches configuration from /api/auth/config:
const config = await fetch('/api/auth/config').then(r => r.json());
const inactivityThreshold = config.inactivity_threshold_minutes; // 20When a user logs in, a JWT token is generated with:
- Standard JWT claims (sub, aud, iat, exp)
- Additional
issued_attimestamp for inactivity tracking - Maximum lifetime of 1 hour (fallback security)
Every authenticated API request is logged with:
- User ID
- Timestamp
- Operation type
- Request details
- Response status
When validating a token, the system:
- Validates standard JWT claims
- Checks user activity from recent logs
- Rejects token if user has been inactive for > 20 minutes
- Logs security events for rejected tokens
The frontend:
- Checks token validity every 30 seconds
- Checks user activity every 2 minutes
- Shows warnings for impending expiration
- Provides clear feedback for inactivity expiration
GET /api/auth/config
Response:
{
"inactivity_threshold_minutes": 20,
"max_token_lifetime_hours": 1,
"features": {
"inactivity_based_expiration": true
}
}GET /api/logs/recent?category=AUDIT&user_id={user_id}
- All authenticated requests are logged
- Logs include user ID, timestamp, and operation details
- Logs are used for inactivity detection only
- No sensitive data is logged
- Tokens still have a maximum lifetime (1 hour)
- Inactivity check is additional security layer
- Failed token validations are logged
- Conservative approach: errors result in token rejection
- Activity logs are stored locally
- No external tracking or analytics
- Users can view their own activity logs
- Logs are rotated and cleaned up automatically
- No interruption during active work
- Tokens remain valid as long as user is active
- Clear warnings before expiration
- Easy refresh functionality
- Automatic logout after 20 minutes of inactivity
- Clear explanation of why session expired
- Simple re-authentication process
- Security benefit of automatic logout
- Clear error messages for inactivity expiration
- Graceful handling of network errors
- Fallback to time-based expiration if needed
- User-friendly recovery options
- Login to the application
- Make some API calls (create nodes, graphs, etc.)
- Wait for 20+ minutes without activity
- Try to make an API call - should be rejected
- Login again - should work normally
Run the test script:
python test_inactivity_expiration.pyThis script:
- Creates a test user
- Makes API calls to generate activity
- Simulates inactivity periods
- Verifies token expiration behavior
-
AUDIT: User activity logs -
SECURITY: Token validation events -
ERROR: Token validation errors
- "Token rejected due to user inactivity"
- "User {user_id} inactive for X minutes"
- "API request: {method} {path}"
# View recent activity logs
curl "http://localhost:8000/api/logs/recent?category=AUDIT&limit=50"
# Check auth configuration
curl "http://localhost:8000/api/auth/config"
# View security events
curl "http://localhost:8000/api/logs/recent?category=SECURITY&limit=20"- Existing tokens will continue to work
- New tokens will use inactivity-based expiration
- No data migration required
- Backward compatible
- Update
backend/routes/users.pyto useInactivityJWTStrategy - Add activity tracking middleware to
backend/main.py - Update frontend auth utilities
- Test thoroughly before deployment
- Configurable Thresholds: Allow users to set their own inactivity threshold
- Activity Types: Different thresholds for different types of activity
- Grace Period: Warning before automatic logout
- Session Recovery: Ability to extend session with password
- Analytics: Activity patterns and usage statistics
- Caching: Cache recent activity for faster checks
- Batch Processing: Process activity logs in batches
- Indexing: Optimize log queries for inactivity checks
- Cleanup: Automatic cleanup of old activity logs
- Check inactivity threshold configuration
- Verify activity logging is working
- Check for network issues affecting API calls
- Verify inactivity check is enabled
- Check log rotation settings
- Ensure activity tracking middleware is active
- Monitor log file sizes
- Check activity log query performance
- Consider reducing log retention period
- Check authentication configuration
- Verify activity logs are being created
- Test token validation manually
- Review security event logs
- Check frontend error handling
The inactivity-based token expiration system provides a better user experience while maintaining security. Active users can work without interruption, while inactive users are automatically logged out for security. The system is configurable, monitorable, and provides clear feedback to users.