Backend & Full Stack Engineer Guide: Fast Ephemeral RSA JWT Fixtures for Django & GraphQL Tests
When testing Django REST or GraphQL APIs secured by OIDC/JWKS bearer tokens, many teams take a dangerous shortcut: they patch out the authentication middleware in pytest and set request.user = test_user directly. That blind spot means broken JWT claim parsers, missing tenant-scope checks, and clock-skew bugs slip straight into production. Conversely, making live network calls to an external OIDC provider during CI slows tests to a crawl. As a backend engineer and full stack engineer, I use session-scoped ephemeral RSA keypairs in pytest to run full cryptographic auth middleware verification in under 1 millisecond per test.
1. Session-Scoped Ephemeral RSA Keypair & Local JWKS Fixture
We generate a single 2048-bit RSA keypair once per test session in memory, point the JWT verifier's public key resolver to that ephemeral public key, and provide a helper factory that mints signed JWTs with arbitrary roles, scopes, and expiration timestamps:
# tests/conftest.py
import time
import jwt
import pytest
from cryptography.hazmat.primitives.asymmetric import rsa
@pytest.fixture(scope="session")
def ephemeral_rsa_keys():
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()
return private_key, public_key
@pytest.fixture
def mint_jwt(ephemeral_rsa_keys, settings):
private_key, public_key = ephemeral_rsa_keys
settings.OIDC_PUBLIC_KEY = public_key
settings.OIDC_AUDIENCE = "https://api.aldianfazrihady.com"
settings.OIDC_ISSUER = "https://auth.aldianfazrihady.com/"
def _make_token(sub: str, tenant_id: str, scopes: list[str], exp_offset_sec: int = 300) -> str:
now = int(time.time())
payload = {
"iss": settings.OIDC_ISSUER,
"aud": settings.OIDC_AUDIENCE,
"sub": sub,
"tenant_id": tenant_id,
"scope": " ".join(scopes),
"iat": now,
"exp": now + exp_offset_sec,
}
return jwt.encode(payload, private_key, algorithm="RS256", headers={"kid": "test-key-1"})
return _make_token
2. Testing Cross-Tenant GraphQL Authorization Boundaries
With real signed tokens flowing through the full ASGI/WSGI middleware stack, every GraphQL mutation test verifies both positive execution and negative cross-tenant isolation (`tenant_id="tenant-b"` attempting to mutate a `tenant-a` resource):
def test_graphql_invoice_mutation_blocks_cross_tenant_jwt(client, mint_jwt, tenant_a_invoice):
attacker_token = mint_jwt(sub="user_99", tenant_id="tenant_b", scopes=["invoices:write"])
response = client.post(
"/graphql/",
data={"query": "mutation($id: ID!) { voidInvoice(id: $id) { ok } }", "variables": {"id": str(tenant_a_invoice.id)}},
content_type="application/json",
HTTP_AUTHORIZATION=f"Bearer {attacker_token}",
)
body = response.json()
assert "errors" in body
assert body["errors"][0]["extensions"]["code"] == "PERMISSION_DENIED"