Testing API Authentication: API Keys, Tokens and OAuth
Almost every real API checks who is calling (authentication) and what they are allowed to do (authorisation). These checks are where many serious bugs hide.
The common types
| Type | How it is sent | Where you see it |
|---|---|---|
| API key | A header like x-api-key: abc123 or a query parameter | Public APIs, server-to-server |
| Basic auth | Authorization: Basic plus base64 of user:password | Old or internal systems |
| Bearer token (often a JWT) | Authorization: Bearer eyJ... | Most web and mobile apps |
| OAuth 2.0 | You get a token from an auth server first, then send it as a bearer token | "Log in with Google", third-party access |
The usual token flow
POST /auth/loginwith email and password.- The response contains a token, for example
{"token": "eyJ..."}. - Every next request sends
Authorization: Bearer <token>. - The token expires after some time and you log in again or use a refresh token.
In Postman, save the token in a variable after login, then set the collection's Authorization tab to "Bearer Token" with {{token}}. Every request in the collection uses it.
What is inside a JWT
A JWT has three parts separated by dots: header, payload and signature. The payload is only base64-encoded, not encrypted, so anyone can read it at jwt.io. Check that it contains no secrets, like passwords, and that it has an expiry (exp).
Authentication test cases
| Test | Expected |
|---|---|
| Correct login | 200 and a token |
| Wrong password | 401 with a message that does not say which field was wrong |
| Request with no token | 401 |
| Token with one character changed | 401 |
| Expired token | 401 |
| Token after logout | 401, if the API supports logout |
| Many wrong passwords in a row | Lockout or 429, per the requirements |
Authorisation test cases
- Log in as user A and request user B's record by id. Expect 403 or 404, never B's data.
- Log in as a normal user and call an admin endpoint. Expect 403.
- Try to change your own role by sending
"role": "admin"in a profile update. It must be ignored.
Keep secrets out of tests: never commit real passwords, API keys or tokens to Git. Read them from environment variables, and keep Postman secrets in the "current value" column, which is not shared.