AlgoViz

API authentication

medium 24 min

Authentication answers one question about every API call: who is asking?

Video lesson · Chapter 1 of 6

From password to an authenticated call

0:00 / 4:26

API authentication

1:16Reel

Theory

Read or listen first. About 2 min.

What it is

Authentication is checking who is making a request. The caller presents a proof, such as a password, a key or a signed token, and the server decides whether to believe it.

It is not the same as authorization, which decides what that caller may do. Authentication comes first and gives authorization a name to work with. The second half has its own topic.

HTTP itself remembers nothing between calls. So every request has to carry its own proof, and most of the design is about what that proof is, how long it lasts and how it can be taken away.

Why it exists

Without it, anyone who knows an address can read or change anyone's data. With it, you can protect accounts, bill customers, limit each caller and write an audit trail with names in it.

There are several methods because callers differ. A program on a server can keep a long secret. A phone in a stranger's pocket cannot. A partner's app should never see your user's password at all.

A short history

  1. May 1996

    HTTP/1.0 (RFC 1945) describes Basic authentication: a user name and password sent with each request.

  2. April 2010

    OAuth 1.0 is published as RFC 5849, so an app can use someone's data without their password.

  3. October 2012

    RFC 6749 publishes OAuth 2.0 and replaces OAuth 1.0.

  4. May 2015

    RFC 7519 standardises JSON Web Token (JWT), a compact signed set of claims.

  5. September 2015

    RFC 7636 adds PKCE, which protects the authorization code in apps that cannot keep a secret.

  6. January 2025

    RFC 9700 collects current OAuth 2.0 security practice: no password grant, and no implicit grant for tokens.

Words to know

Credential
The proof a caller presents: a password, key, token or certificate.
Bearer token
A token that works for whoever holds it, like cash. Keep it secret and send it only over HTTPS.
Claim
One statement inside a token, such as sub (who), aud (for which service) or exp (until when).
Access token
A short-lived token sent with API calls.
Refresh token
A longer-lived token used only to get a new access token.
OAuth 2.0
A standard way to let an app act with limited access, without sharing a password.
OpenID Connect
A login layer on top of OAuth 2.0. Its ID token says who the user is.
Revocation
Making a credential stop working before it expires.

How it works

Step through the idea, or press Play.

Step 1 of 3

Present. The caller sends a proof with the request

Understand it

Start here

The hotel story

Think of a hotel. You prove who you are once, at the front desk. After that you carry a key card, and each door reads the card without phoning the desk.

One identity check, then a key card
FRONT DESKIDWho are you?

The ID card is authentication. Which doors the key card opens is authorization.

Authentication

  • Verifies identity: who you are
  • Fails with 401, and the response must carry a WWW-Authenticate header
  • Examples: login, API key, JWT, certificate
  • Sends Authorization: Bearer <token>

Authorization (next topic)

  • Checks permission: what you may do
  • Fails with 403
  • Examples: roles, scopes, access lists
  • Example: role admin may delete a product

Choices

Four common methods

  • API keys

    A long random string that names a calling program. Best between servers. Simple, but anyone holding the key is you.

  • Session cookies

    A random ID in a cookie. The server looks up the session. Best for your own web app, and easy to end.

  • Signed tokens (JWT)

    A token that carries its own claims and a signature. Best across many services. Hard to take back early.

  • OAuth 2.0

    A way to give an app limited access without a password. Best for third parties and for single sign-on with OpenID Connect.

Side by side

API keySessionJWTOAuth 2.0
EffortLowLowMediumHigh
Server lookup per callYes, the key recordYes, the sessionNoDepends: none for a JWT, one for an opaque token
Grows to many serversWith a shared or cached key storeWith a shared session storeNaturallyNaturally with JWT
Revoke nowEasyEasyHard without a denylistEasy for refresh tokens, hard for JWT access tokens
Names a personNo, names an appYesYes, if it has subWith OpenID Connect
Third-party accessNoNoNot by itselfYes
Best forServer to serverYour own websiteMobile apps, many servicesPartners, social login
JWT is a token format. OAuth 2.0 is a way to obtain tokens. They are often used together.

Which one do I need?

Method 1

API keys

An API key is a random string that identifies the calling application. It is the simplest method and gives limited protection: no person is named, and a leaked key works until someone turns it off.

How a key is used

  1. 1

    Generate

    A developer creates a key in the dashboard. Show it once, then store only its SHA-256 hash and a short visible prefix.

  2. 2

    Send

    The client adds it to each request, for example X-API-Key: demo_key_EXAMPLE_not_real.

  3. 3

    Validate

    The server hashes what it received, finds the record, and checks that it is active.

  4. 4

    Proceed

    The request continues with the app's identity, its limits and its permissions.

Where to put the key

PlaceVerdictWhy
Header: X-API-Key or AuthorizationUse thisStays out of URLs, browser history and most access logs. Make sure your own logs drop it too
Query parameter: ?api_key=AvoidURLs are written to logs, history and shared links
Request bodyAvoidNot standard, and GET requests normally have no body

Do

  • Different keys for development and production
  • Rotate keys, with two active during the change
  • Keep keys in a secret manager or environment variables
  • Limit rate and permissions per key
  • Set an expiry date

Do not

  • Commit keys to version control
  • Share one key between services
  • Put a secret key in frontend or mobile code
  • Use one key for all customers

Good points

  • Simple to add and to use
  • Works well between servers
  • Easy to revoke and rotate
  • No redirects or complex flows

Weak points

  • Names an app, not a person
  • A leak means full access until revoked
  • Can end up in logs and URLs
  • No expiry unless you build one

Why a random key needs only a fast hash

2128/21012 guesses/s≈1.7×1026 s≈5×1018 years\frac{2^{128}/2}{10^{12}\ \text{guesses/s}} \approx 1.7 \times 10^{26}\ \text{s} \approx 5 \times 10^{18}\ \text{years}
With 128 random bits, guessing is hopeless even at an assumed 101210^{12} tries a second. People's passwords are short and guessable, so they need a slow hash such as Argon2id, scrypt or bcrypt.

Method 2

Sessions

After login the server stores a session and sends a random ID in a cookie. Every later request is one lookup. A shared store such as Redis lets any server answer, so sessions do scale. Logging out deletes the row, and it takes effect at once.

Method 3

JSON Web Tokens

A JWT is a signed note with three parts: header, payload, signature. The server needs no stored session, because the facts are in the token and the signature shows that nobody changed them.

Text
HEADER      {"alg": "HS256", "typ": "JWT"}                 which algorithm signed itPAYLOAD     {"iss": "https://auth.shop.example",           who issued it             "aud": "orders-api",                          who it is for             "sub": "user_123", "role": "customer",        who it is about             "exp": 1735689600}                            until when (seconds)SIGNATURE   HMAC-SHA256( base64url(header) + "." + base64url(payload), secret )
The three parts, joined by dots when sent. All values are invented.

Size of a JWT

len(n)=⌈4n3⌉36+240+43+2=321 bytes\text{len}(n) = \left\lceil \tfrac{4n}{3} \right\rceil \qquad 36 + 240 + 43 + 2 = 321 \text{ bytes}
A 27-byte header, a 180-byte payload and a 32-byte HS256 signature, plus two dots. With a 256-byte RS256 signature the last part is 342, for a total of 620 bytes on every call.

The flow

  1. 1

    Login

    The user sends credentials over HTTPS: POST /auth/login.

  2. 2

    Create

    The server checks them and signs a token with user, audience and expiry.

  3. 3

    Return

    It sends an access token and a refresh token.

  4. 4

    Store

    A browser keeps the access token in memory and the refresh token in an HttpOnly cookie. A phone uses its keychain. Not localStorage, which any injected script can read.

  5. 5

    Send

    Each call carries Authorization: Bearer <token>.

  6. 6

    Verify

    The API checks algorithm, signature, issuer, audience and expiry, then uses sub.

Login, then a call

The database is asked only at login. Later calls are checked with arithmetic.

Access token and refresh token

Access tokenRefresh token
LifeShort: 5 to 60 minutes, often 15Long: days or weeks
Sent toEvery API callOnly the token endpoint
HoldsIdentity and limited permissionsA random value, or a pointer to a session
StoredIn memoryHttpOnly cookie, or the phone's keychain
RevokeWait for expiry, or a denylistDelete it on the server

JWT strengths

  • No session storage for access checks
  • Any instance or service can verify it
  • Carries the user, so no lookup is needed
  • Not tied to one domain's cookies

JWT costs

  • Cannot be revoked early without a denylist
  • Larger than a session ID
  • Readable by whoever holds it
  • Refresh and key rotation to build

Ending access

Revocation and rotation

How long a stolen access token lives

Tmax⁡=L=15 minTavg=L2=7.5 minT_{\max} = L = 15 \text{ min} \qquad T_{\text{avg}} = \frac{L}{2} = 7.5 \text{ min}
With lifetime LL and theft at a random moment. Shorter tokens cut the damage and cost more refreshes: 900,000 active users with 15-minute tokens cause 900,000/900=1,000900{,}000 / 900 = 1{,}000 refreshes a second.

Refresh token rotation with reuse detection

A refresh token works once. Seeing an old one again means two parties hold it, so the whole family ends.

Ways to end access early

WayTakes effectCost
Short expiry onlyWithin the token's lifeNothing extra
Denylist of token IDs (jti)At onceOne fast lookup per call; entries can be dropped after expiry
User's token version in a cacheAt once, for all devicesOne lookup per call
Rotate the signing keyAt once, for everyoneAll users log in again: for emergencies

Method 4

OAuth 2.0 and OpenID Connect

OAuth 2.0 lets a user give an app limited access to their data without sharing a password. It is about access, not login. Buttons such as "Sign in with Google" use OpenID Connect, which adds an ID token that says who the user is.

Four roles

RoleDoesExample
Resource ownerOwns the dataYou
ClientAsks for accessThe ShopEasy app
Authorization serverAsks for consent, issues tokensGoogle's OAuth server
Resource serverHolds the dataA Google API

Authorization code flow with PKCE

The code passes through the browser, the tokens do not. state ties the answer to this browser; the verifier proves that the same app started the flow.

Grant types today

GrantUse it forNote
Authorization code + PKCEAll apps with usersPKCE is required for public clients and recommended for all (RFC 9700)
Authorization code without PKCEOlder web apps with a backendSecret stays on the server; add PKCE
Client credentialsMachine to machineNo user is involved
Device authorizationTelevisions and command linesUser confirms on another device
ImplicitAvoidToken appears in the URL; use code with PKCE
PasswordNeverThe app sees the password; RFC 9700 says it must not be used

OAuth strengths

  • Users never give a third party their password
  • Narrow access through scopes
  • A widely used standard
  • Users can withdraw consent

OAuth costs

  • Easy to get wrong: use a tested library
  • Redirects need exact, registered addresses
  • Several grant types to choose from
  • Tokens to store, refresh and revoke

Architecture

Where the check happens

One issuer, many verifiers

Clients log in at the auth service, which reads the user database and keeps refresh tokens in Redis. Clients call the API gateway with an access token. The auth service publishes its public keys. The gateway reads those keys, checks each token, and forwards verified calls to the orders and cart services.
Only the auth service holds the private signing key. Everyone else holds public keys, so a broken service cannot issue tokens.

Keys

Who can verify, and who can issue

Sharing the trust between services

SigningWho can verifyWho can issueUse
HS256 (one shared secret)Everyone with the secretEveryone with the secretOne service talking to itself
RS256 or ES256 (key pair)Everyone, with the public keyOnly the holder of the private keyMany services
Mutual TLSBoth ends of the connectionYour certificate authorityService to service
Python
import base64, hashlib, hmac, json, secretsKEY = secrets.token_bytes(32)      # made fresh for this run, never in codedef b64(raw): return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()def unb64(s): return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))def mac(text): return hmac.new(KEY, text.encode(), hashlib.sha256).digest()def sign(claims):    head = b64(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())    body = b64(json.dumps(claims).encode())    return f"{head}.{body}.{b64(mac(head + '.' + body))}"def verify(token, now, iss="auth", aud="orders-api"):    head, body, sig = token.split(".")    if json.loads(unb64(head)).get("alg") != "HS256": return "wrong algorithm"    if not hmac.compare_digest(mac(head + "." + body), unb64(sig)): return "bad signature"    c = json.loads(unb64(body))    if c.get("iss") != iss or c.get("aud") != aud: return "not for us"    if c.get("exp", 0) <= now: return "expired"    return c["sub"]t = sign({"iss": "auth", "aud": "orders-api", "sub": "user_123", "exp": 1000})print(verify(t, now=900), "|", verify(t, now=1000), "|", verify(t, 900, aud="cart-api"))h, _, s = t.split(".")forged = b64(json.dumps({"sub": "admin"}).encode())print(verify(f"{h}.{forged}.{s}", now=900))
Check everything, and choose the algorithm yourself. Use a tested library in production.
Edit and run it in your browser

Failures

What goes wrong

MistakeResultFix
Trusting the alg in the tokenA forged token may passAllow a fixed list of algorithms
Skipping aud or issA token for another service works hereCheck both, every time
Accepting a refresh token as an access tokenA week-long pass to every endpointUse separate audiences or types, and check them
Different answers for unknown user and wrong passwordAttackers learn which accounts existSame message, similar time
No limit on login attemptsPasswords can be guessedLimit per account and per address; offer passkeys or a second factor
Clocks that disagreeValid tokens rejectedSync clocks, allow about 30 seconds

What the server answers

Summary

The whole topic in one minute.

Pick the proof from the caller. A server gets a key or client credentials, your own web app gets a session cookie, your own mobile app gets short access tokens with rotating refresh tokens, and a third party gets OAuth 2.0.

A signed token can be checked without a lookup, and that is exactly why it is hard to take back. Keep it short, check every claim, and keep something on the server that you can revoke.

  • Authentication asks who; failing it is 401. Authorization asks what; failing it is 403.
  • API keys name programs. Store only hashes, send them in headers, rotate them.
  • A JWT is header, payload, signature: signed, readable, and hard to revoke, so keep it short.
  • OAuth 2.0 gives limited access without a password. OpenID Connect adds login. Use the code flow with PKCE.
  • Always HTTPS, never a secret in frontend code, and always something on the server you can revoke.

Sources