Skip to content
Index Ai Academy
Phase 8 · Security & reliability

Authentication and authorization

API keys, sessions, tokens and OAuth: who's calling, and what may they do?

About 45 minutes · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers7

First principles

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.

  1. Starting point

    A signed token identifies user A

  2. What changes

    Look up the requested record and check ownership

  3. Result

    The policy denies A access to B's private record

Compare all three steps
  1. Starting point

    A signed token identifies user A

  2. What changes

    Look up the requested record and check ownership

  3. Result

    The policy denies A access to B's private record

Complete and reverse the trace

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.

Compare with the worked step

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.

Check one starting point

A signed token identifies user A. Check that your implementation produces the result shown above.

Try it on a new case

Which check catches an authenticated user requesting someone else's private record?

Show worked reasoning

An authorization check on the specific record catches it. The token can be valid while the requested access is denied.

Run, change, and build

Check this when debugging. Thinking a decoded JWT is a verified JWT.

Trace the cause · HTTP request, job, and result
  1. Identify the request, response, and any durable state. Predict the status or stored result before following the trace.
  2. Change one request property and keep the client contract visible. Compare the response and job state to explain the observed behavior.
  3. Try the same reasoning on this case. Which check catches an authenticated user requesting someone else's private record?

Why it matters

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.

What you'll be able to do

  • Tell authentication (who is calling) from authorization (what they may do)
  • Issue and check API keys safely, storing only their hashes
  • Sign and verify a token (JWT) from scratch, and forge one against a weak verifier
  • Explain sessions, scopes, object-level checks (BOLA) and the OAuth authorization code flow
Quick check
At a hotel, the front desk checks your ID, and your key card opens only your room. Which part is authorization?
  1. The hotel's name on the sign outside the door
  2. Paying for the room when you leave
  3. The front desk checking your photo ID at check-in
  4. The key card opening only the rooms you may enter
Show the answer

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.

The idea: who is calling, and what may they do

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:

  • Authentication (often "authn"): proving who is calling, with a key, a password or a token. That's the ID check.
  • Authorization ("authz"): deciding what that caller may do. Read campaigns? Delete them? This particular campaign? That's the key card.

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".

Quick check
A request arrives with a valid key that isn't allowed to delete campaigns. Which status?
  1. 401 Unauthorized
  2. 404 Not Found
  3. 403 Forbidden
  4. 400 Bad Request
Show the answer

403 Forbidden

The server knows who is calling, and the answer is no.

Credentials, and how to store them

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.

Quick check
Why is it fine to store API keys with fast SHA-256, when passwords need slow hashes?
  1. SHA-256 is already slow enough to stop guessing, so a slower hash adds nothing
  2. API keys never leak, since they're only ever sent over HTTPS connections
  3. It isn't fine: API keys need a slow hash such as bcrypt, just like passwords
  4. API keys are long random strings, so even billions of guesses per second never find one
Show the answer

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:

stylewhat's sentwhere you'll see it
API keya long random secret in Authorization: Bearer ... or a header like X-API-Keyone program calling another: model providers, payment APIs
HTTP BasicAuthorization: Basic + user:password, base64-encodedold internal tools, simple admin endpoints
Bearer tokena short-lived token from a sign-in step, often a signed JWTmobile and single-page apps after login; OAuth
Session cookiea cookie the browser sends automaticallyclassic 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.

Try it now

Who is calling, how often, and from where decides the style.

Sessions, for browsers

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.
Quick check
What does the HttpOnly setting on a cookie stop?
  1. The cookie from ever expiring
  2. Other sites' requests carrying it
  3. Page scripts reading the cookie
  4. The cookie going over plain HTTP
Show the answer

Page scripts reading the cookie

With HttpOnly, a script injected into the page can't read the session cookie and send it elsewhere.

Signed tokens: JWT

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.
Quick check
A token's payload says "exp": 1793000000. A request arrives at Unix time 1793000600. What should the server do?
  1. Accept it, because the signature is still valid
  2. Reject it: the token expired 10 minutes ago
  3. Look the user up in the database to decide
  4. Accept it and move exp forward
Show the answer

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.

Quick check
Recall: compare signatures with 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))
  1. 64 True
  2. 64 None
  3. 32 False
  4. 64 False
Show the answer

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.

Quick check
What does this print?
import base64, json
payload = base64.urlsafe_b64encode(json.dumps({"sub": "ada"}).encode()).decode()
print(json.loads(base64.urlsafe_b64decode(payload))["sub"])
  1. sub
  2. an error
  3. None
  4. ada
Show the answer

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.

Quick check
Anyone can decode a JWT and read its payload. What stops them changing "role": "user" to "role": "admin"?
  1. The payload is encrypted, so an edit would turn it into unreadable bytes
  2. Nothing: anyone can make themselves an admin, so JWTs can't be trusted
  3. Browsers block any edits to the tokens they store for a website
  4. The signature: the server rejects a token whose payload no longer matches it
Show the answer

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.

Authorization: scopes, roles and ownership

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.

Quick check
A logged-in customer changes /orders/ord_51 in the URL to /orders/ord_52, which belongs to someone else. What should the API do?
  1. Return it, because the customer is logged in
  2. Refuse it: logged in isn't the same as owning it
  3. Return it without the price
  4. Log the customer out
Show the answer

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.

In your own words
What is the difference between authentication and authorization, and what stops someone editing a token's payload?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: keys, tokens and an attack

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]))
It runs right here in your browser, with nothing to install.

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
Drill

Read a Bearer token

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"))
In the lesson, your code is checked as you write it.

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.

Worked example

A JWT is signed, not secret

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)))
In the lesson you can change this and run it.

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.

The checks you must never skip, and the attack on a weak verifier

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:

  1. The token has exactly three parts, and the header's alg is the one you expect. Never let the token choose.
  2. The signature matches, compared with hmac.compare_digest.
  3. exp is in the future, allowing a few seconds of clock leeway between servers.
  4. aud is your API, and iss (the issuer) is the one you trust. A token made for another service must not work on yours.
  5. Only then, read sub and scope and authorize.
Quick check
A token's header says "alg": "none" and its signature part is empty. A verifier that obeys the header accepts it. What went wrong?
  1. The signature was too short, so the check was skipped
  2. The token had expired
  3. The token chose its own rule, so anyone can forge one
  4. The secret was too weak
Show the answer

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.

Quick check
A JWT's signature is valid, but its aud is billing.shop.test and your API is api.shop.test. What should your API do?
  1. Accept it, because the signature proves it's genuine
  2. Accept it, but allow only read requests
  3. Reject it, because it was issued for another service
Show the answer

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.

Drill

Who may read this invoice?

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"}))
In the lesson, your code is checked as you write it.
In your own words
Which checks must a token pass before you trust its claims, and who chooses the algorithm?

Write a sentence or two, then compare it with a good answer in the lesson.

In AI and ML systems: whose key, whose data, whose budget

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.

OAuth: access on someone's behalf

"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.

Where this shows up in an engineer's week

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.

In your own words
Why does a valid token still need an ownership check, and where does that matter for a model-backed feature?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 4 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

A request arrives with no credentials at all. Which status fits?

  1. 401 Unauthorized
  2. 403 Forbidden
  3. 404 Not Found
  4. 400 Bad Request

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 8 · about 23 hours of study

APIs

Design, build, secure and scale web APIs from first principles 27 lessons 1 free
  1. HTTP from the wire up FreeWhat really travels between client and server: bytes, headers and bodies.40 min
  2. API stylesREST, RPC, GraphQL, gRPC and streaming: what each is for.35 min
  3. Build an API server from scratchRouting, handlers and responses, with no framework.45 min
  4. A web framework, from the insideDecorators, middleware and error handling: how Flask and FastAPI work.40 min
  5. Designing a REST APIResources, methods, status codes, errors and pagination done well.45 min
  6. Validating requests with schemasCheck every request against a JSON Schema and say exactly what's wrong.45 min
  7. A database-backed APICRUD endpoints on SQLite, with safe concurrent updates.45 min
  8. Authentication and authorizationAPI keys, sessions, tokens and OAuth: who's calling, and what may they do?45 min
  9. Rate limits, retries and idempotencyKeep an API up under load and make retries safe.45 min
  10. Async HTTP clientsMany requests at once with asyncio and httpx: limits, timeouts and retries.45 min
  11. Webhooks and eventsPush events to other systems: signed, retried and deduplicated.45 min
  12. Documenting APIs with OpenAPIA machine-readable contract for docs, SDKs and AI tools.40 min
  13. Running APIs in productionVersioning, CORS, caching, request ids and health checks.45 min
  14. Project: a reviews APIAn authenticated, validated, paginated API with tests.45 min
  15. Web pages with FlaskRoutes, Jinja templates, a shared layout, links and error pages, tested with the test client.45 min
  16. Forms and redirectsGET and POST, validation messages, post/redirect/get, flash messages and CSRF tokens.45 min
  17. Accounts and loginsPassword hashing with bcrypt, sessions, pages that need a login, and safe logout.45 min
  18. Project: a trail log web appA multi-page app with a database, accounts, forms and tests.45 min
  19. JavaScript for Python programmersVariables, functions, arrays and objects mapped from Python, and the traps: truthy empty arrays, for...in and string sort.35 min
  20. Async JavaScript: promises, await and fetchThe event loop, async and await, fetch with res.ok checks, Promise.all, and timeouts with AbortController.35 min
  21. Modules, Node and reading TypeScriptimport and export, package.json, classes, and types as notes the compiler checks, read through a small tool server.30 min
  22. A chat front end in the browserThe DOM and events, model text kept out of innerHTML, a streamed reply parsed from server-sent events, and a Stop button.40 min
  23. APIs with FastAPITyped routes, pydantic models, automatic validation and docs, tested with httpx.45 min
  24. Streaming from the serverServer-sent events written by a server: an ASGI app that sends a body in pieces, FastAPI's StreamingResponse, heartbeats, and what a closed connection looks like.40 min
  25. Project: a FastAPI service with accountsA session per request, bcrypt sign-ups, signed tokens, ownership checks and tests on a fresh database.45 min
  26. Serving a model behind FastAPILoad once with lifespan, a typed predict route, a batch route, a cap on work in flight, 429 with Retry-After, a readiness route and a 202 job.45 min
  27. Capstone: a streaming chat serviceA FastAPI service with key auth, a per-user bucket, a token budget, request ids and an event-stream reply, tested on fresh state.45 min
Part of a free course 127 lessons

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.

Part of a free course 20 lessons

Build and Operate HTTP APIs

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