How to mock short TTL access tokens in Python
Simulate short-lived access tokens with a TTL, issue and validate them, and watch expiry behavior.
Python code
33 linesimport time
import uuid
from datetime import datetime, timedelta
class AccessTokenManager:
def __init__(self, ttl_seconds=30):
self.ttl_seconds = ttl_seconds
self.tokens = {}
def issue_token(self):
token_id = uuid.uuid4().hex
expiry = datetime.now() + timedelta(seconds=self.ttl_seconds)
self.tokens[token_id] = expiry
return token_id
def validate_token(self, token_id):
if token_id not in self.tokens:
return False
if datetime.now() > self.tokens[token_id]:
del self.tokens[token_id]
return False
return True
if __name__ == "__main__":
manager = AccessTokenManager(ttl_seconds=2)
token = manager.issue_token()
print(f"Token issued: {token}")
print(f"Immediately valid: {manager.validate_token(token)}")
time.sleep(3)
print(f"After TTL expired, valid: {manager.validate_token(token)}")
Output
Token issued: a3f1c2e4b5d6f7a8b9c0d1e2f3a4b5c6
Immediately valid: True
After TTL expired, valid: False
How it works
The AccessTokenManager stores tokens in a dictionary mapping token IDs to their expiry datetime. When validating, it checks if the token exists and if the current time is past the expiry; expired tokens are removed on validation. The datetime.now() comparison leverages Python's built-in datetime arithmetic. In a real system, you'd persist tokens and use a secure hash, but this mock is ideal for testing token lifecycle logic.
Common mistakes
- Using `time.sleep` in production code instead of a real token store.
- Not cleaning up expired tokens, causing memory leaks.
- Assuming token IDs are unique without checking for collisions (though uuid4 avoids this).
Variations
- Use `time.monotonic()` to avoid clock adjustments affecting expiry.
- Store tokens in Redis with a native TTL for distributed systems.
Real-world use cases
- Testing authentication middleware that rejects requests with expired tokens.
- Simulating OAuth2 access token expiry in integration tests.
- Developing a local mock server for API clients that handle token refresh.
Sponsored
More from Auth & security at scale
- ACME LetsEncrypt Mock Challenge Server in Python medium
- AES GCM encryption and decryption in Python medium
- Build a Mock OIDC Userinfo Endpoint in Python with Flask easy
- ChaCha20-Poly1305 mock in Python medium
- ECDH key agreement in Python with cryptography medium
- Enforce TLS 1.2 Minimum in Python easy
Keep learning
Related tutorials and quizzes for this topic.