Testing API Keys, Basic Auth and Custom Tokens

Many APIs still rely on simpler authentication mechanisms like API keys, Basic Auth, or custom header tokens. These schemes are easier to implement but also easy to misuse. Proper testing ensures that keys and credentials are handled safely and consistently across endpoints.

Testing API Keys and Basic Auth

API keys are often passed in headers or query parameters, while Basic Auth encodes username and password in a header. Tests should verify that requests without valid credentials fail with appropriate status codes (such as 401 or 403) and that valid credentials work across all protected endpoints.

# Example: API key in header

curl -i   -X GET "https://api.example.com/v1/customers"   -H "X-Api-Key: <api_key>"
Note: For Basic Auth, ensure that HTTPS is enforced so credentials are not exposed in plain text over the network.
Tip: Create separate test accounts or keys with different privilege levels so you can verify that each key sees only the data and actions it is supposed to.
Warning: Passing API keys in query parameters can leave them in logs and browser history. If the system supports this pattern, highlight it as a risk and test how logs are handled.

Custom token headers may use schemes like X-Auth-Token or similar. Make sure error messages do not leak sensitive information when tokens are invalid. Also check how quickly tokens can be revoked or rotated.

Revocation and Rotation Tests

Tests should include revoking or regenerating keys and verifying that old keys stop working promptly. This is critical for incident response scenarios where keys may be compromised. Automated tests can simulate rotation by creating a new key, updating configuration, and confirming that calls using the old key fail.

Common Mistakes

Mistake 1 โ€” Using the same high-privilege key for all tests

This hides permission issues and increases risk.

โŒ Wrong: One powerful key that can do everything in all environments.

โœ… Correct: Use multiple keys with scoped privileges to test behaviour realistically.

Mistake 2 โ€” Not testing key revocation and expiry

Ignoring lifecycle events leaves gaps in security coverage.

โŒ Wrong: Assuming keys work forever and revocation will be handled later.

โœ… Correct: Design tests that cover key rotation, expiration, and invalidation.

🧠 Test Yourself

What is important when testing API keys and Basic Auth?