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.

Easy Python 3.9+ Aug 9, 2026 Auth & security at scale 15 views 0 copies

Python code

33 lines
Python 3.9+
import 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

stdout
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

  1. Use `time.monotonic()` to avoid clock adjustments affecting expiry.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Auth & security at scale

Related tutorials and quizzes for this topic.