API testing · mid
API authentication and expiring tokens
Tests that log in once and run for a long time meet expired tokens. A token manager fixes this without slowing the suite.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- A JWT is header.payload.signature in base64url. The payload has exp, the expiry time. The error body or the WWW-Authenticate header can also say the token expired.
- A sign of expiry: failures always start the same time after login. The suite grew and a hidden assumption broke.
- Fix: a token manager that caches a token per user or role with its expiry, and gets a new one (refresh token or client-credentials call) when less than about a minute is left.
- In REST Assured use a filter or a shared request spec that asks the manager for the header on every request.
- Make the refresh thread-safe with a lock, so eight threads do not all log in together and hit rate limits.
- Do not log in for every test. It is slow and can trigger login rate limits or lock accounts.
- Use a test account per role and key tokens by role, such as tokenFor(Role.ADMIN).
- Secrets come from CI variables or a vault. Never copy a token from Postman into code.
The red pen
Common traps: mistake → fix
Mistake: Ask for a token that never expires in test
Fix: it hides a real behaviour and you never test refresh.
Mistake: Log in before every request
Fix: it is slow and can lock the account.
Mistake: A token copied from Postman into code is fine
Fix: it expires and it is a secret in git.
Easy to hard
Questions interviewers ask, easy to hard
- Your API suite fails after 15 minutes with 401. How do you find the cause?
- Design a token manager for 8 parallel threads.
- What is inside a JWT and which field tells the expiry?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.