REAL-WORLD SCENARIOS

Testing OAuth-Protected APIs Without Hardcoding Tokens

Hardcoded tokens in test files look harmless until they aren't. A Bearer token pasted into a fixture works for a while, then expires, and the suite starts failing in a way that looks like a flaky network or a broken deploy. The token wasn't flaky; it was dead. The real problem is that the suite had no strategy for OAuth credentials at all.

The fix is a deliberate pattern: tests request a token at runtime, reuse it while it's valid, and read credentials only from the environment or a secrets store, never from source code. That pattern matters even more once coding agents work in your repository. An agent that hits a 401 while iterating will look for a way to make the test pass, and pasting a token it found in a terminal or a .env file into a test is a very available shortcut. Agents also read files and print output freely, so anywhere a secret is lying around is somewhere it can end up in a log, a commit or a prompt.

In this article I'll show how I acquire OAuth tokens in pytest fixtures, handle expiry without re-authenticating on every test, keep credentials out of code and CI logs, and set up the guardrails that keep both people and agents away from real secrets.

Build an API Automation Framework With Node.js

Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.

Learn more

Fetch the token once, in a session fixture

The natural home for token acquisition is a session-scoped fixture: one request to the identity provider per run, shared by every test that needs it. For a client-credentials flow:

# conftest.py
import os

import pytest
import requests


def fetch_token() -> dict:
    response = requests.post(
        os.environ["OAUTH_TOKEN_URL"],
        data={
            "grant_type": "client_credentials",
            "client_id": os.environ["OAUTH_CLIENT_ID"],
            "client_secret": os.environ["OAUTH_CLIENT_SECRET"],
            "scope": os.environ.get("OAUTH_SCOPE", "api.read"),
        },
        timeout=10,
    )
    response.raise_for_status()
    payload = response.json()
    assert isinstance(payload.get("access_token"), str) and payload["access_token"], \
        "token endpoint returned no access_token"
    return payload


@pytest.fixture(scope="session")
def auth_headers():
    return {"Authorization": f"Bearer {fetch_token()['access_token']}"}

Every credential comes from os.environ with no hardcoded fallback. If a variable is missing, setup fails immediately with a KeyError naming it, which is a much clearer signal than a mysterious 401 twenty tests later. raise_for_status() does the same for a rejected token request, and the assertion catches a 200 that didn't include a usable token.

One provider-specific detail: some identity providers expect the client ID and secret as HTTP Basic authentication rather than in the form body. With requests that's auth=(client_id, client_secret) on the POST. Check your provider's documentation; the rest of the pattern doesn't change.

Refresh before expiry, not on every test

A session token works for short runs. If the suite runs longer than the token's lifetime, you'll eventually see 401s partway through. Dropping the fixture to function scope "fixes" that by fetching a token for every test, which slows the run and can get you rate-limited by the identity provider. A small manager that refreshes only when needed is better:

# auth_utils.py
import threading
import time


class TokenManager:
    def __init__(self, fetch, skew_seconds: int = 60):
        self._fetch = fetch
        self._skew = skew_seconds
        self._token = None
        self._expires_at = 0.0
        self._lock = threading.Lock()

    def token(self) -> str:
        with self._lock:
            if time.monotonic() >= self._expires_at - self._skew:
                payload = self._fetch()
                self._token = payload["access_token"]
                self._expires_at = time.monotonic() + int(payload.get("expires_in", 300))
            return self._token
# conftest.py
from auth_utils import TokenManager

_tokens = TokenManager(fetch_token)


@pytest.fixture
def auth_headers():
    return {"Authorization": f"Bearer {_tokens.token()}"}

The fixture is function-scoped again, so each test gets a fresh header, but the identity provider is only called when the token is close to expiry. The skew margin covers clock differences and requests already in flight. If the provider omits expires_in, the fallback assumes a short lifetime so you refresh early rather than late.

A note on parallel runs: pytest-xdist runs workers as separate processes, so each worker gets its own manager and its own token. That's usually fine; it just means one token request per worker. The lock protects against threads within one process, which matters if your tests use a thread pool. For how expiry shows up differently across environments, see diagnosing token expiry failures across test environments.

Keep credentials out of code and CI logs

Locally, I use a .env file loaded by python-dotenv, and .env goes into .gitignore before anything is written to it:

# conftest.py
from dotenv import load_dotenv

load_dotenv()  # loads .env if present; does nothing if the file is missing

In CI there's no file; the pipeline injects the variables from its secrets store. In GitHub Actions:

jobs:
  api-tests:
    runs-on: ubuntu-latest
    env:
      OAUTH_TOKEN_URL: ${{ secrets.OAUTH_TOKEN_URL }}
      OAUTH_CLIENT_ID: ${{ secrets.OAUTH_CLIENT_ID }}
      OAUTH_CLIENT_SECRET: ${{ secrets.OAUTH_CLIENT_SECRET }}
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install -r requirements.txt
      - run: pytest tests/

GitHub masks secret values in logs, but masking is a safety net, not a design. A few more guardrails:

  • Dedicated test clients with the minimum scopes, revocable without touching production.
  • Never log the Authorization header. Verbose HTTP logging will print it happily; redact it in your logging setup before turning debug logging on.
  • Never pass secrets as command-line arguments, where they can show up in process listings and shell history.
  • Scan for leaks. If a token did reach a commit, deleting it in a later commit doesn't remove it from history. Keeping test secrets out of your version control history covers cleanup and prevention.

Guardrails for coding agents

When Copilot or another coding agent runs your suite, treat it like a new teammate who reads everything and is very keen to get tests green. Three things help.

Write the rules down. In .github/copilot-instructions.md or your agent's equivalent:

## Authentication in tests
- Tokens come only from the auth_headers fixture. Never write a token, client secret
  or Authorization value into any file.
- Do not open, print or summarise .env or any secrets file.
- A 401 or 403 is a real signal: report it with the endpoint and expected scope.
  Do not bypass auth, mock it out, or skip the test to make the run pass.

Give the agent its own low-privilege credentials. If an agent runs tests in a sandbox or CI job, use a test client with read-only or narrowly scoped access in a non-production environment. If anything leaks, the damage is small and you can revoke one client.

Check generated diffs for secrets. A pre-commit secret scanner catches the obvious cases, and a quick search of the diff for Bearer and eyJ, the typical start of a JWT, catches many of the rest.

If your product has its own agent that calls OAuth-protected APIs on a user's behalf, test the other direction too: the token must never reach the model. Call the agent's tools directly and assert that neither their return values nor the recorded trace contain the access token:

def test_tool_output_never_contains_token(orders_tool, user_session):
    result = orders_tool(session=user_session, status="open")
    assert user_session.access_token not in repr(result)

It's a simple deterministic check, and it guards against a tool that helpfully echoes request headers back into the conversation.

Build it once

Getting OAuth right in a test suite isn't glamorous, but it pays back every time a token rotates, a CI job runs cleanly, or a new teammate, human or agent, can run the suite without anyone sending them a secret. If you'd like to build this into a complete framework with Behave or Cucumber and GitHub Copilot, my API testing courses cover authentication and fixtures step by step.