Quality is not optional. It's our standard. Free QA tools for testers and developers.

OAuth Test Data for Tokens, Scopes, and Expiration Cases

QTQA3 Team

OAuth Test Data for Tokens, Scopes, and Expiration Cases

OAuth‑based APIs are the backbone of most modern services, yet the test data that drives their verification is often an after‑thought. A token that looks valid on the surface can hide subtle bugs: wrong audience, missing scope, clock‑skew handling, or an expiration that falls on a leap‑second boundary. This post walks through a repeatable process for creating realistic OAuth test data, shows a worked example you can copy into a CI job, and highlights the traps that bite teams the most.


Why OAuth Test Data Is Hard

ChallengeWhat It Looks Like in ProductionWhy It Breaks Tests
Multiple token formatsJWT, opaque reference tokens, MAC tokensParsers expect different claims; a single generator must emit all three.
Scope granularityread:orders write:customers admin:*Authorization logic often branches on individual scope strings, not just “has‑scope”.
Time‑based claimsexp, nbf, iat expressed as Unix secondsClock drift, leap seconds, and test‑time manipulation make static values brittle.
Audience & issuer validationaud: "api.example.com", iss: "auth.example.com"Mismatched values trigger 401/403 that look like bugs in the consumer.
Revocation & introspectionToken revocation lists, introspection endpointsTests that only check signature miss revocation paths.
Key rotationJWKS endpoint rotates every 24 hA static key set becomes stale, causing signature verification failures.

If you treat OAuth test data as “just a string”, you will spend more time debugging flaky tests than writing new ones.


Decision Criteria for Test Data Generation

Before you pick a tool or write a script, answer these questions. The answers shape the data model you will feed to the generator.

QuestionDecision Impact
Which token formats must be covered?Determines whether you need JWT claim sets, opaque identifiers, or both.
What scope taxonomy does the API use?Drives the combinatorial matrix (e.g., role‑based vs. resource‑based scopes).
How many expiration scenarios are required?Minimum: valid, expired, not‑yet‑valid. Add near‑expiry and clock‑skew if you test refresh logic.
Do you need key rotation simulation?If yes, generate a JWKS with multiple keys and a kid rotation schedule.
Is introspection/revocation part of the contract?Include a revocation list or an introspection payload in the data set.
What environments consume the data?Unit tests (in‑process), contract tests (PACT), load tests (k6, Locust), or manual exploratory sessions.
How often does the data need to refresh?Daily CI runs → generate on‑the‑fly; nightly performance runs → pre‑seed a static file.

Write the answers down as a short “test‑data spec”. It becomes the single source of truth for reviewers and for any automated generator you adopt.


Workflow for Generating OAuth Test Data

1. Capture the spec  →  2. Choose a generator  →  3. Parameterise the generator
4. Emit artefacts (JSON, JWKS, CSV)  →  5. Validate artefacts  →  6. Publish to test environments

1. Capture the Spec

Create a oauth-test-spec.yaml (or JSON) that enumerates:

tokenFormats:
  - jwt
  - opaque
scopes:
  - read:orders
  - write:orders
  - admin:*
expirationScenarios:
  - name: valid
    offsetMinutes: 30
  - name: expired
    offsetMinutes: -10
  - name: notYetValid
    offsetMinutes: 60
  - name: nearExpiry
    offsetMinutes: 2
  - name: clockSkewPositive
    offsetMinutes: 5   # token exp in future, but test clock +5 min
  - name: clockSkewNegative
    offsetMinutes: -5  # token exp in past, but test clock -5 min
keyRotation:
  enabled: true
  keys: 3
  rotationHours: 24
introspection:
  enabled: true
  revokedTokens: 2

2. Choose a Generator

  • Custom script (Python/Node) – full control, but you maintain it.
  • Open‑source libraries – jose (Node), python-jose, go-jose. Good for JWT only.
  • QA3 free test data generator – /tools/test-data-generator – supports JWT, opaque tokens, scope matrices, and expiration offsets in a single UI or CLI call.

Pick the option that matches the “maintenance budget” column in your spec.

3. Parameterise the Generator

Map each spec field to a generator flag. Example CLI for the QA3 tool:

qa3-test-data generate \
  --formats jwt,opaque \
  --scopes "read:orders,write:orders,admin:*" \
  --expiration-scenarios valid,expired,notYetValid,nearExpiry,clockSkewPositive,clockSkewNegative \
  --key-rotation --keys 3 --rotation-hours 24 \
  --introspection --revoked 2 \
  --output oauth-test-data.json

4. Emit Artefacts

Typical output includes:

FileContents
tokens.jsonArray of token objects: { "format": "jwt", "raw": "...", "claims": {...}, "scenario": "valid" }
jwks.jsonPublic key set with kid values matching the JWT kid header.
introspection.jsonMapping token → { active: true/false, scopes: [...], exp: ... }.
revocation-list.txtOne opaque token per line for revocation endpoint tests.

5. Validate Artefacts

Run a contract validation step before the artefacts enter CI:



# 1. Schema check (JSON Schema for tokens.json)


ajv validate -s token-schema.json -d tokens.json


# 2. Signature verification (spot‑check 5 JWTs)


node verify-jwt.js tokens.json


# 3. Expiration logic sanity


python check_expirations.py tokens.json

Fail the pipeline if any check errors.

6. Publish to Test Environments

  • Unit / contract tests – load tokens.json as fixtures.
  • Load tests – feed the raw token strings into the request builder.
  • Exploratory sessions – copy a few tokens into Postman/Insomnia collections.

Automate the publish step (e.g., aws s3 cp to a bucket mounted by test runners) so the data is always fresh.


Worked Example: Generating a Complete Token Set

Below is a complete, runnable example that you can drop into a GitHub Actions workflow. It uses the QA3 generator (CLI) because it covers all required formats in one call.

1. Add the Generator to the Runner



# .github/workflows/oauth-test-data.yml


name: Generate OAuth Test Data


on:
  schedule:
    - cron: '0 2 * * *'   # daily at 02:00 UTC
  workflow_dispatch: {}


jobs:
  generate:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repo
        uses: actions/checkout@v4


- name: Install QA3 CLI
        run: |
          curl -fsSL https://qa3.io/cli/install.sh | bash
          echo "$HOME/.qa3/bin" >> $GITHUB_PATH


- name: Generate test data
        env:
          QA3_API_KEY: ${{ secrets.QA3_API_KEY }}
        run: |
          qa3-test-data generate \
            --formats jwt,opaque \
            --scopes "read:orders,write:orders,admin:*" \
            --expiration-scenarios valid,expired,notYetValid,nearExpiry,clockSkewPositive,clockSkewNegative \
            --key-rotation --keys 3 --rotation-hours 24 \
            --introspection --revoked 2 \
            --output ./generated/oauth-test-data.json


- name: Validate artefacts
        run: |
          # schema validation
          npx ajv validate -s schemas/token-schema.json -d generated/oauth-test-data.json
          # spot‑check signatures
          node scripts/verify-jwt.js generated/oauth-test-data.json
          # expiration sanity
          python scripts/check_expirations.py generated/oauth-test-data.json


- name: Upload artefacts
        uses: actions/upload-artifact@v4
        with:
          name: oauth-test-data
          path: generated/
          retention-days: 7

2. Token Schema (schemas/token-schema.json)

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "array",
  "items": {
    "type": "object",
    "required": ["format", "raw", "claims", "scenario"],
    "properties": {
      "format": { "enum": ["jwt", "opaque"] },
      "raw": { "type": "string", "minLength": 10 },
      "claims": {
        "type": "object",
        "required": ["iss", "aud", "exp", "iat", "scope"],
        "properties": {
          "iss": { "type": "string", "format": "uri" },
          "aud": { "type": "string", "format": "uri" },
          "exp": { "type": "integer", "minimum": 0 },
          "iat": { "type": "integer", "minimum": 0 },
          "scope": { "type": "string" },
          "kid": { "type": "string" }
        }
      },
      "scenario": { "type": "string" }
    }
  }
}

3. Spot‑Check Signature Verification (scripts/verify-jwt.js)

// verify-jwt.js
const fs = require('fs');
const jose = require('jose');
const jwks = JSON.parse(fs.readFileSync('generated/jwks.json', 'utf8'));
const tokens = JSON.parse(fs.readFileSync('generated/oauth-test-data.json', 'utf8'));


const keyStore = jose.createRemoteJWKSet(new URL('file://' + __dirname + '/../generated/jwks.json'));


(async () => {
  let failures = 0;
  for (const t of tokens.filter(x => x.format === 'jwt').slice(0, 5)) {
    try {
      await jose.jwtVerify(t.raw, keyStore, { issuer: t.claims.iss, audience: t.claims.aud });
      console.log(`✅ ${t.scenario} – signature ok`);
    } catch (e) {
      console.error(`❌ ${t.scenario} – ${e.message}`);
      failures++;
    }
  }
  process.exit(failures > 0 ? 1 : 0);
})();

4. Expiration Sanity Check (scripts/check_expirations.py)



# check_expirations.py


import json, time, sys


data = json.load(open('generated/oauth-test-data.json'))
now = int(time.time())
errors = []


for t in data:
    exp = t['claims'].get('exp')
    nbf = t['claims'].get('nbf', 0)
    scenario = t['scenario']


if scenario == 'valid':
        if not (nbf <= now < exp):
            errors.append(f'{scenario}: token not valid now (exp={exp}, nbf={nbf})')
    elif scenario == 'expired':
        if not (exp < now):
            errors.append(f'{scenario}: token not expired (exp={exp})')
    elif scenario == 'notYetValid':
        if not (now < nbf):
            errors.append(f'{scenario}: token already valid (nbf={nbf})')
    elif scenario == 'nearExpiry':
        if not (0 < exp - now <= 120):
            errors.append(f'{scenario}: not near expiry (exp={exp})')
    # clock‑skew scenarios are validated by the test harness that shifts the clock


if errors:
    for e in errors:
        print('❌', e, file=sys.stderr)
    sys.exit(1)
print('✅ All expiration scenarios consistent')

Running the workflow produces a fresh oauth-test-data.json plus jwks.json and introspection.json every night. Downstream jobs (contract tests, load tests) simply download the artefact and consume the raw token strings.


Validation Checks Checklist

Use this checklist each time a new data set lands in CI. It catches the most common regressions before they reach a test run.

  • Schema compliance – every token object matches token-schema.json.
  • Signature verification – at least 5 JWTs per key (kid) verify against the published JWKS.
  • Claim completeness – iss, aud, exp, iat, scope present on every JWT.
  • Scope matrix coverage – each defined scope appears in at least one token per scenario.
  • Expiration logic – valid, expired, notYetValid, nearExpiry tokens behave as expected against a fixed clock.
  • Clock‑skew tokens – clockSkewPositive expires after the test clock +5 min; clockSkewNegative expires before the test clock –5 min.
  • Key rotation – JWKS contains the declared number of keys; each JWT kid matches one of them.
  • Introspection payload – active flag matches revocation list; scope array matches token’s scope string.
  • Revocation list – every token listed as revoked returns active: false from the introspection endpoint.
  • Opaque token format – length ≥ 32 chars, URL‑safe base64, no . separators.

Automate the checklist as a single script that exits non‑zero on any failure; wire it into the same workflow that generates the data.


Common Pitfalls and How to Avoid Them

PitfallSymptomRoot CauseMitigation
Static exp valuesTests pass today, fail tomorrowHard‑coded Unix timestamps in fixturesAlways generate exp relative to now (offset minutes).
Missing kid in JWT headerSignature verification fails intermittentlyGenerator omitted kid when key rotation enabledEnforce kid in generator config; validate header in checklist.
Scope string vs. array mismatchAuthorization middleware returns 403Token carries scope: "read:orders write:orders" but introspection returns ["read:orders","write:orders"]Normalise to a single representation in the spec; generate both forms if the API expects both.
Clock‑skew not exercisedRefresh‑token flow never tested under driftTest harness uses system clock onlyInject a configurable clock wrapper (e.g., timekeeper in Node, freezegun in Python) and drive it with the skew scenarios.
Revocation list out of syncRevoked token still returns active: trueGenerator created revocation list but introspection stub wasn’t updatedGenerate introspection payload and revocation list from the same source of truth.
Opaque token collisionTwo tests receive the same opaque token, causing cross‑talkRandom generator without uniqueness guaranteeUse UUIDv4

Read more

Generate Realistic API Error Payloads for Negative Testing

A practical guide to “Generate Realistic API Error Payloads for Negative Testing,” with worked scenarios, tool considerations, validation checks, and actionable advice for QA teams.

Idempotency Test Data for Safe API Retry Testing

A practical guide to “Idempotency Test Data for Safe API Retry Testing,” with worked scenarios, tool considerations, validation checks, and actionable advice for QA teams.

Rate-Limit Test Data for 429 and Retry-After Validation

A practical guide to “Rate-Limit Test Data for 429 and Retry-After Validation,” with worked scenarios, tool considerations, validation checks, and actionable advice for QA teams.