API authentication
medium 24 minAuthentication answers one question about every API call: who is asking?
See it run
Follow a credential from login to the check on every call, and see how it ends.
Operations
Log in, then call
A password is checked once. After that a signed token goes with each call.
Step 1 of 9
Enter credentials
The user types an email and password in the app.
Step 1: Enter credentials
def login(email, password, now): user = find_user(email) or DUMMY if not same(slow_hash(password, user.salt), user.hash): return 401 return access(user.id, now), refresh_token(user.id, now)def call(request, now): status, who = authenticate(request.header, now) if status != 200: return status return handle(request, who)- Lookup per call
- None
- Ends early
- Hard
- Session
- one lookup per call, ends at once
Say what is checked on every call: algorithm, signature, issuer, audience, expiry.
In the real world
The same api authentication doing real jobs. Pick one and step through it.
Why an access token should be short.
Step 1 of 3
12:04, log out
The refresh token is deleted. No new access token can be made.
Step 1: 12:04, log out
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Trusting an ID from the request
criticalAnyone can type another person's number. The caller comes from the verified credential.
Wrongorders = find(request.body["user_id"])Rightwho = verify(request.token)orders = find(who)Decoding without verifying
criticalAnyone can write a payload. Only the signature shows who made it.
Wrongclaims = decode(token) # no key usedRightclaims = verify(token, KEY, algorithms=["HS256"], issuer=ISS, audience=AUD)Accepting a refresh token as an access token
criticalIf both are signed the same way and nothing tells them apart, a seven-day token opens every endpoint.
Wrongaccess = sign({"sub": u})refresh = sign({"sub": u}, days=7)Rightaccess = sign({"sub": u, "aud": "api"}, minutes=15)refresh = random_token() # opaque, stored as a hashStoring API keys as plain text
majorOne leaked backup then exposes every customer.
Wrongdb.insert(key=key)Rightdb.insert(prefix=key[:8], hash=sha256(key))
Interview tips
Explain it in one line
- Authentication: who are you? 401.
- Authorization: what may you do? 403.
Choose by caller
- Server: key or client credentials.
- Your website: session cookie.
- Your app: short token and refresh.
- Third party: OAuth code with PKCE.
Give numbers
- Access token about 15 minutes.
- Average exposure is half of that.
- 900,000 users refreshing every 900 s is 1,000 a second.
Expect these questions
- How do you log out everywhere?
- How do you rotate the key?
- What if a token is stolen?