Token Management¶
Core token structure and lifecycle management across all implementations.
Token Structure¶
All implementations use a unified token structure with the following fields:
| Field | Type | Description |
|---|---|---|
access_token |
string | The OAuth access token |
token_type |
string | Token type (usually "Bearer") |
expires_in |
int | Token lifetime in seconds |
refresh_token |
string | Optional refresh token |
scope |
string | Token scope |
expires_at |
datetime/timestamp | Calculated expiration timestamp |
Token Lifecycle¶
1. Creation¶
Tokens are created after successful OAuth flow:
2. Expiration Check¶
All implementations include a 10% buffer before actual expiration:
def is_expired(self) -> bool:
buffer = self.expires_in * 0.1
return datetime.now() >= (self.expires_at - timedelta(seconds=buffer))
This prevents race conditions where the token expires during a request.
3. Serialization¶
Tokens can be serialized to JSON for storage:
Best Practices¶
Secure Storage¶
Security
Always store tokens securely with restricted permissions (0600 on Unix).
Token Refresh¶
Check expiration before each use:
Error Handling¶
Handle token-related errors gracefully:
FileNotFoundError/ENOENT: No cached tokenJSONDecodeError: Corrupted token fileExpired: Token needs refresh