Free Python developer course
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
API keys, sessions, tokens and OAuth: who's calling, and what may they do?
What can a valid identity tell you about access to one specific record?
Authentication establishes who is calling. Authorization also checks the operation against that identity and the targeted resource's policy or owner.
A signed token identifies user A
Look up the requested record and check ownership
The policy denies A access to B's private record
A signed token identifies user A
Look up the requested record and check ownership
The policy denies A access to B's private record
Given A signed token identifies user A and The policy denies A access to B's private record, write down the missing step that connects them.
Look up the requested record and check ownership
Now take Look up the requested record and check ownership and the result above. Write an input and an implementation that could produce this trace.
A signed token identifies user A. Check that your implementation produces the result shown above.
Which check catches an authenticated user requesting someone else's private record?
An authorization check on the specific record catches it. The token can be valid while the requested access is denied.
Check this when debugging. Thinking a decoded JWT is a verified JWT.
Every useful API has to answer two questions on every request: who is this, and are they allowed to do this? Getting either wrong is how data leaks. The most common serious API flaw is checking that a user is logged in, without checking that the record is theirs. You'll configure these same mechanisms for model APIs, MCP servers and agents, and in Phase 9 you'll meet them again, guarding remote MCP servers.
The key card opening only the rooms you may enter
Authentication proves who you are (the ID at the desk); authorization decides what you may do (which doors your card opens). APIs check both on every request, and most serious leaks are authorization mistakes.
This rests on HTTP from the wire up: every credential here travels in a header of the request you parsed.
Picture a hotel. At the front desk you show your ID, which proves who you are. You get a key card, which opens your room and the gym, but not the room next door. APIs make the same split:
They fail differently. A missing or bad credential is 401 Unauthorized. Despite the name, it's about authentication. A valid credential without permission is 403 Forbidden.
In plain words: 401 means "I don't know who you are". 403 means "I know who you are, and the answer is no".
403 Forbidden
The server knows who is calling, and the answer is no.
An API key is the simplest credential for one program calling another: a long random secret the client sends with every request, usually as Authorization: Bearer sk_live_51Hx.... Done well, you generate it with secrets (32 random bytes or more), show it once, and store only a hash of it. A hash is a one-way fingerprint: easy to compute from the key, with no way back, so a leaked database does not leak the keys. A fast hash like SHA-256 is fine for keys, unlike for passwords, because a long random key can't be guessed however fast the hash is. Keep a short prefix visible so people can tell keys apart, give each key scopes (what it may do), and let owners revoke and rotate it.
API keys are long random strings, so even billions of guesses per second never find one
Slow hashing defends weak, human-chosen secrets. A 32-byte random key has far too many possibilities to guess.
An API's docs say which of four styles it uses:
| style | what's sent | where you'll see it |
|---|---|---|
| API key | a long random secret in Authorization: Bearer ... or a header like X-API-Key | one program calling another: model providers, payment APIs |
| HTTP Basic | Authorization: Basic + user:password, base64-encoded | old internal tools, simple admin endpoints |
| Bearer token | a short-lived token from a sign-in step, often a signed JWT | mobile and single-page apps after login; OAuth |
| Session cookie | a cookie the browser sends automatically | classic websites |
Base64 is an encoding, not encryption: anyone who sees a Basic header turns it back into the password in one line, so Basic auth is only acceptable over HTTPS. A request with no credential gets 401 and a WWW-Authenticate header naming the style it expects.
Who is calling, how often, and from where decides the style.
People in a browser don't paste API keys. Think of a coat check instead: you hand over your coat once, get a numbered ticket, and from then on the ticket is all you show.
After someone logs in, the server creates a session: a random id stored on the server, sent to the browser in a cookie. The browser attaches that cookie to every request automatically. Three cookie settings matter:
HttpOnly: page scripts can't read it, so a script injected into the page can't steal it.Secure: only sent over HTTPS.SameSite=Lax (or Strict): not sent on most requests started by other sites. That blocks cross-site request forgery, where a hostile page makes your browser send a request with your cookie.HttpOnly setting on a cookie stop?Page scripts reading the cookie
With HttpOnly, a script injected into the page can't read the session cookie and send it elsewhere.
A coat-check ticket means nothing without the rack behind it. A festival wristband is different: a guard at any gate can read it and trust it with no list to check, because it's hard to fake.
A JSON Web Token (JWT, said "jot") is that wristband. It carries claims, which are facts about the caller, signed so nobody can change them. It's three parts joined by dots, header.payload.signature, each written in base64url, a way to write any data as letters and digits that are safe in a URL. Here are the header and the payload, decoded:
{"alg": "HS256", "typ": "JWT"}
{
"sub": "user_42",
"scope": "campaigns:read campaigns:write",
"aud": "api.shop.test",
"exp": 1793000000
}
sub (subject): who the token is about. aud (audience): which API it's meant for.exp: when it expires, in seconds since 1970 (a Unix timestamp). iat: when it was issued.scope: space-separated permissions."exp": 1793000000. A request arrives at Unix time 1793000600. What should the server do?Reject it: the token expired 10 minutes ago
1793000600 is 600 seconds after exp, so the token expired 10 minutes earlier. A valid signature only proves nobody changed the token, not that it's still current.
The signature is an HMAC of header.payload, a fingerprint that takes a secret to make. With HS256, only the server knows that secret. With RS256 or ES256 it's a public-key signature instead, which others can check without the secret.
The server can check a JWT without a database lookup. That's why JWTs are popular. It's also their weakness. A wristband keeps working until it expires, even if the person was thrown out. So keep lifetimes short, often minutes, and pair them with a refresh token: a longer-lived token that can be revoked and is used to get new short ones.
hmac.compare_digest. An HMAC is a fingerprint that takes a secret to make. What does this print when one word of the message is changed?import hashlib, hmac secret = b"server-secret" message = b'{"sub": "ada", "role": "user"}' signature = hmac.new(secret, message, hashlib.sha256).hexdigest() tampered = b'{"sub": "ada", "role": "admin"}' check = hmac.new(secret, tampered, hashlib.sha256).hexdigest() print(len(signature), hmac.compare_digest(signature, check))
64 False
A SHA-256 fingerprint is 64 hex characters, and changing one word of the message gives a completely different one. Nobody can make the matching fingerprint for the changed message without the secret. That is all the signature on a token is: change the payload, and it no longer matches.
import base64, json payload = base64.urlsafe_b64encode(json.dumps({"sub": "ada"}).encode()).decode() print(json.loads(base64.urlsafe_b64decode(payload))["sub"])
ada
Encoding and decoding gives back the same dictionary, and ["sub"] reads ada. Anyone can read a JWT's payload. It's signed, not secret, so never put secrets in it.
"role": "user" to "role": "admin"?The signature: the server rejects a token whose payload no longer matches it
The signature covers the payload, and only the key holder can make a new one. Never put secrets in a JWT: signed isn't secret.
Scopes limit what a credential may do: campaigns:read but not campaigns:write. Roles group permissions for people: viewer, editor, admin.
The check that's forgotten most is object-level. Back at the hotel, your key card is real, and it opens guest rooms. It still shouldn't open room 412 when you're staying in 410. The caller may read campaigns, but is cmp_103 theirs? Without that check, changing the id in the URL shows another customer's data. This is broken object-level authorization (BOLA), first on the OWASP API Security Top 10, a widely used list of the most serious API flaws. It is also called IDOR (insecure direct object reference). BOLA and IDOR are one hole with two names, and this course says BOLA.
In plain words: being logged in isn't enough. Each time someone asks for a record, check that the record belongs to them.
/orders/ord_51 in the URL to /orders/ord_52, which belongs to someone else. What should the API do?Refuse it: logged in isn't the same as owning it
Every request for a record must check that the record belongs to the caller: WHERE id = ? AND account_id = ?. Skipping that is the top flaw on the OWASP API list.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a key you can issue and check. The cell shows the key once and stores only its hash and prefix.
import hashlib, hmac, secrets def new_api_key(): key = "sk_live_" + secrets.token_urlsafe(32) record = { "prefix": key[:12], "hash": hashlib.sha256(key.encode()).hexdigest(), "scopes": ["campaigns:read"], } return key, record # give key to the user once; save only record def check_key(presented, records): digest = hashlib.sha256(presented.encode()).hexdigest() for r in records: if hmac.compare_digest(digest, r["hash"]): return r return None key, record = new_api_key() print("show once:", key[:16] + "...") print("stored: ", record["prefix"], record["hash"][:16] + "...") print(check_key(key, [record]) is not None, check_key("sk_live_guess", [record]))
Basic auth is a two-line cell, which shows why it is not secret:
import base64 token = base64.b64encode(b"trail-admin:s3cret-pass").decode() print({"Authorization": f"Basic {token}"}) print(base64.b64decode(token).decode()) # anyone can do this
Write bearer_token(header): given the Authorization header (or None), return the token from Bearer <token>. The scheme is case-insensitive. Raise AuthError if the header is missing, uses another scheme, or doesn't have exactly a scheme and one non-empty token.
class AuthError(Exception): pass def bearer_token(header): return header.split(" ")[1] print(bearer_token("Bearer sk_live_51Hx"))
The stepper builds a token the way the picture did: encode the header, encode the payload, sign the two joined with a dot. Watch each part appear, and notice that the signature is computed from the other two.
Anyone can read a JWT's payload. Only the server's secret can make a valid signature.
import base64, json token = ("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." "eyJzdWIiOiJ1c2VyXzQyIiwic2NvcGUiOiJjYW1wYWlnbnM6cmVhZCIsImF1ZCI6" "ImFwaS5zaG9wLnRlc3QiLCJleHAiOjE3OTMwMDAwMDB9." "yFdRQOSJULhBBr5EPk7OOZObYRhixQeP57Pf_1NsAlI") def b64url_decode(part): return base64.urlsafe_b64decode(part + "=" * (-len(part) % 4)) header, payload, signature = token.split(".") print(json.loads(b64url_decode(header))) print(json.loads(b64url_decode(payload)))
No key was needed to read it. Base64 is an encoding, not encryption, so never put secrets in a JWT. Decoding is not verifying, either: the signature is real for the secret demo-secret, but the code never checked it. A server must recompute the signature and compare before trusting a single claim.
Most JWT security bugs are a skipped check. A guard who looks at a wristband's color but not its date lets in last year's crowd. Verify, in order:
alg is the one you expect. Never let the token choose.hmac.compare_digest.exp is in the future, allowing a few seconds of clock leeway between servers.aud is your API, and iss (the issuer) is the one you trust. A token made for another service must not work on yours.sub and scope and authorize."alg": "none" and its signature part is empty. A verifier that obeys the header accepts it. What went wrong?The token chose its own rule, so anyone can forge one
A verifier must decide which algorithm it accepts. If the token picks, an attacker picks "none" and needs no secret.
Old libraries broke rule 1: a token could say "alg": "none", meaning no signature, and the verifier obeyed. The cell forges such a token against a weak verifier, then runs it through a strong one.
import base64, hashlib, hmac, json SECRET = b"demo-secret" def b64url(data): return base64.urlsafe_b64encode(data).decode().rstrip("=") def b64url_decode(part): return base64.urlsafe_b64decode(part + "=" * (-len(part) % 4)) def weak_verify(token): head, payload, sig = token.split(".") if json.loads(b64url_decode(head))["alg"] != "none": # the token picks the rule signed = f"{head}.{payload}".encode() good = b64url(hmac.new(SECRET, signed, hashlib.sha256).digest()) if not hmac.compare_digest(good, sig): raise ValueError("bad signature") return json.loads(b64url_decode(payload)) def strong_verify(token): head, payload, sig = token.split(".") if json.loads(b64url_decode(head))["alg"] != "HS256": # you pick the rule raise ValueError("unexpected algorithm") signed = f"{head}.{payload}".encode() good = b64url(hmac.new(SECRET, signed, hashlib.sha256).digest()) if not hmac.compare_digest(good, sig): raise ValueError("bad signature") return json.loads(b64url_decode(payload)) head = b64url(json.dumps({"alg": "none", "typ": "JWT"}).encode()) body = b64url(json.dumps({"sub": "user_42", "scope": "admin"}).encode()) forged = f"{head}.{body}." print("weak accepts:", weak_verify(forged)) try: strong_verify(forged) except ValueError as e: print("strong refuses:", e)
The forged token has no signature at all, and the weak verifier made the admin out of anyone. The fix is one line: the verifier decides which algorithms it accepts.
aud is billing.shop.test and your API is api.shop.test. What should your API do?Reject it, because it was issued for another service
A valid signature proves who issued the token. The aud claim says who it was issued for, and a token meant for another service mustn't work on yours.
Write invoice_status(user, invoice): user has id, role and a list of scopes; invoice has owner. Return 403 if the user lacks the invoices:read scope; otherwise 200 if the user owns the invoice or is an "admin"; otherwise 404, so strangers can't even learn that the invoice exists.
def invoice_status(user, invoice): return 200 ana = {"id": "u_1", "role": "member", "scopes": ["invoices:read"]} print(invoice_status(ana, {"id": "inv_77", "owner": "u_2"}))
Write a sentence or two, then compare it with a good answer in the lesson.
A model API call uses your service's key, an API key kept in an environment variable and never in code. The users of your product are a different layer: they sign in, and each one is a caller you authorize. That matters for AI work in three ways. Per-user budgets attach to an authenticated identity (a key or a token's sub), so an account is where a token quota lives. Object-level checks protect what a model reads: a retrieval route that fetches documents for a prompt must filter by owner, or one user's files end up in another's answer. And agents that call tools do so on someone's behalf, which is what OAuth is for.
"Let this app read my Google Calendar" is OAuth 2.0. Think of the valet key some cars come with: it starts the car but won't open the trunk, and you never hand over your own keys. The app gets limited access and never sees your password. This lesson shows the shape of the authorization code flow; Securing remote servers with OAuth builds it for remote MCP servers, step by step.
PKCE (said "pixy") protects the redirect. The app makes a random secret, sends only its hash, and proves it knows the secret when it swaps the code for a token. It is like keeping one half of a torn ticket: a stolen code is useless without your half. The picture shows what travels and what each side holds.
Three habits. Check ownership on every query: WHERE id = ? AND account_id = ?, so changing an id in a URL, or a retrieval route fetching a document for a prompt, can't reach another account's record. Keep tokens short-lived and pair them with a refresh token that can be revoked, since a JWT works until exp even if the person was thrown out. Keep secrets out of tokens: a JWT is signed, not secret, and so is a prompt log. Goes deeper in: Project: a FastAPI service with accounts puts these checks in a real service, Securing remote servers with OAuth guards a remote MCP server with OAuth, and [[p11-security-ops]] covers rotating and auditing keys.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
A request arrives with no credentials at all. Which status fits?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Design, test, deploy, and operate an HTTP API that another engineer can use.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write