SyntaxPilot
Courses/Cybersecurity Fundamentals/Lesson 32
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Cybersecurity Fundamentals · Lesson 32 of 90

OAuth 2.0 explained

delegated authorizationresource ownerclientauthorization serverresource serveraccess tokenscopesconsentauthorization code flowPKCEclient credentials flowdevice authorization flowdeprecated implicit and password grantsredirect URI validation

These are the notes for Cybersecurity Fundamentals (defensive), episode 32. Episode 31 built safe tokens. Today's question: how do you let one app use another app for you, without handing over your password? That's OAuth 2.0, the system behind every "Allow access?" screen. We invent it one problem at a time: delegated authorization; the four roles (resource owner, client, authorization server, resource server); access tokens, scopes and consent; the authorization code flow with its front channel and back channel; the state parameter; redirect URI validation; public vs confidential clients and PKCE; the client credentials flow; the device authorization flow; token introspection; the deprecated implicit and password grants; and OAuth 2.1. Every term is explained the first time it appears, and the Glossary at the end defines them all again.

Neha, PrintKaro, QuizMasti, Ravi Photos, every URL, code and secret here are made up, and everything runs locally on toy data: the "servers" are Python functions in one file. Every code sample runs with Python 3.13 (standard library only); outputs are real, copied from actual runs (tokens and codes are random on every run).

The problems you'll solve

Problem Idea it teaches
A print site asks for your photo-app password Why sharing passwords fails: all-or-nothing, no per-app revocation
Give the print site only what it needs Delegated authorization, the four roles, access token, scope, consent
Getting the token to the app without leaking it Authorization code flow, front channel, back channel, one-time code
An attacker pushes their own code into your session The state parameter, CSRF
The code is sent to the attacker's address Redirect URI registration and exact matching
Phone apps can't keep a secret Public vs confidential clients, code interception, PKCE
A TV with no keyboard Device authorization flow
A program with no user Client credentials flow, token introspection
Old shortcuts still in tutorials Deprecated implicit and password grants, OAuth 2.1

Problem 1: "just give us your password"

Neha wants a printed album of her Goa trip from PrintKaro, a different company. Her photos live in Ravi Photos. The obvious way: PrintKaro asks for her Ravi Photos password, logs in as her, and saves the password to fetch photos again later.

Demo 1: what a password lets an app do

# The obvious way: give the print site your PASSWORD. Toy local "photo app".
photos = ["goa1.jpg", "goa2.jpg", "diwali.jpg"]
password = "Neha@Goa2026"

def photo_api(pwd, action):
    if pwd != password: return "401 wrong password"
    if action == "read":   return f"200 {photos}"
    if action == "delete": photos.clear(); return "200 all photos deleted"
    if action == "change_password": return "200 password changed"

printkaro_saved = password                     # the print site STORES it
print("PrintKaro reads:  ", photo_api(printkaro_saved, "read"))
print("PrintKaro deletes:", photo_api(printkaro_saved, "delete"))   # a bug, or a breach
print("PrintKaro could:  ", photo_api(printkaro_saved, "change_password"))
# The only way to stop it: change your password, and re-type it in EVERY other app

Output:

PrintKaro reads:   200 ['goa1.jpg', 'goa2.jpg', 'diwali.jpg']
PrintKaro deletes: 200 all photos deleted
PrintKaro could:   200 password changed

Why it fails:

  • A password is all or nothing: every action, forever.
  • Neha can't take back one app's access; she must change her password and retype it in every other app.
  • A breach at PrintKaro leaks her password (and maybe every other site where she reused it).
  • Her MFA (episode 29) can't help an app that logs in as her.

Problem 2: delegated access (the valet key)

Some cars come with a valet key: it starts the car but won't open the boot or the glovebox. That's the whole idea of OAuth.

Valet key story OAuth 2.0 role In our example
You, the car's owner Resource owner: the person who owns the data and decides Neha
The valet Client: the app that wants access (never the person) PrintKaro
The hotel desk that hands out the valet key Authorization server: checks who you are, asks your permission, issues tokens login.ravi.example
The car, which obeys the key Resource server: holds the data, checks the token on every request Ravi Photos API
The valet key itself Access token: a limited, expiring, revocable permission photos:read token

Letting someone act for you with limited rights is delegated authorization. OAuth 2.0 is defined in RFC 6749 (October 2012): it lets a third-party application obtain limited access to an HTTP service, either on behalf of a resource owner or on its own behalf. It replaced OAuth 1.0 (RFC 5849).

  • A scope is a named permission the client asks for, like photos:read. Scope names are chosen by each service.
  • The authorization server shows a consent screen: "PrintKaro wants to view your photos. Allow?" Consent means the user approves exactly those scopes.
  • Golden rule for app builders: ask for the fewest scopes the job needs (least privilege, episode 3).

Demo 2: a scoped, revocable token

# The fix: a limited ACCESS TOKEN with SCOPES, that you can revoke. Toy local server.
import secrets
photos = ["goa1.jpg", "goa2.jpg", "diwali.jpg"]
tokens = {}                                    # the authorization server's records

def issue(client, scopes):                     # after Neha says "yes" on the consent screen
    t = secrets.token_urlsafe(12); tokens[t] = {"client": client, "scope": scopes, "active": True}
    return t

def photo_api(token, action):                  # the resource server
    rec = tokens.get(token)
    if not rec or not rec["active"]: return "401 invalid_token"
    if f"photos:{action}" not in rec["scope"]: return "403 insufficient_scope"
    return f"200 {photos}" if action == "read" else "200 done"

t = issue("printkaro", {"photos:read"})
print("read:   ", photo_api(t, "read"))
print("delete: ", photo_api(t, "delete"))
tokens[t]["active"] = False                    # Neha clicks "remove access" in settings
print("after revoke:", photo_api(t, "read"), "| Neha's password: unchanged")

Output:

read:    200 ['goa1.jpg', 'goa2.jpg', 'diwali.jpg']
delete:  403 insufficient_scope
after revoke: 401 invalid_token | Neha's password: unchanged
Status Meaning When
401 Unauthorized Your credentials are missing or invalid Revoked, expired or made-up token
403 Forbidden We know who you are, but you're not allowed Token lacks the needed scope

Problem 3: getting the token to the app (the authorization code flow)

After Neha clicks Allow, her browser is sent back to PrintKaro. The obvious way to deliver the token is to put it in that web address (printkaro.example/cb#access_token=...). But URLs get copied everywhere: browser history, server logs, and the Referer header (the header that tells the next site which page you came from). A bearer token in a URL is a leaked token.

The fix: put only a short-lived, one-time code in the URL, and let PrintKaro's server swap it for the token over a direct connection.

The five steps

 Neha's browser            PrintKaro server               Ravi login (authorization server)     Ravi Photos API
      |  1. redirect to /authorize?response_type=code&client_id=printkaro
      |       &redirect_uri=https://printkaro.example/cb&scope=photos:read&state=K71G...  ------->|
      |  2. Neha logs in AT RAVI and clicks Allow  <------------------------------------------->|
      |  3. redirect to https://printkaro.example/cb?code=BY1k...&state=K71G...   (front channel)
      |------------------------>|
      |                         |  4. POST /token  code + client_id + client_secret   (back channel)
      |                         |-------------------------------------------------->|
      |                         |  5. {"access_token": ..., "token_type": "Bearer"} |
      |                         |<--------------------------------------------------|
      |                         |  6. GET /photos  Authorization: Bearer ...  ------------------------------->|
  • Front channel: messages carried through the user's browser (redirects). Visible, copyable, can be tampered with.
  • Back channel: a direct server-to-server HTTPS call. The browser never sees it.
  • The authorization code is short-lived (about a minute) and works once.
  • The client secret is a password for the app itself, known only to PrintKaro's server.
  • state: a random value PrintKaro stores (tied to Neha's browser session) before step 1 and checks when the browser returns. Without it, an attacker could make Neha's browser complete a login with the attacker's code, so Neha's PrintKaro session silently uses the attacker's photo account (a form of CSRF, cross-site request forgery, where another site makes your browser send a request). RFC 9700 says clients MUST prevent CSRF, using PKCE or a one-time state.

Demo 3: the flow, simulated

# Authorization code flow, simulated locally: front channel (browser) + back channel (server to server)
import secrets
codes = {}
def authorize(client_id, redirect_uri, scope, state):       # authorization server, after consent
    code = secrets.token_urlsafe(6); codes[code] = {"client": client_id, "scope": scope}
    return f"{redirect_uri}?code={code}&state={state}"       # browser is sent back here

def token_endpoint(code, client_id, client_secret):          # back channel: never in the URL bar
    rec = codes.pop(code, None)                              # pop = a code works ONCE
    if rec is None or rec["client"] != client_id or client_secret != "pk-secret-91":
        return {"error": "invalid_grant"}
    return {"access_token": secrets.token_urlsafe(8), "token_type": "Bearer", "scope": rec["scope"]}

session_state = secrets.token_urlsafe(6)                     # client remembers this per user
back = authorize("printkaro", "https://printkaro.example/cb", "photos:read", session_state)
print("1 browser lands on:", back)
code, state = [kv.split("=")[1] for kv in back.split("?")[1].split("&")]
print("2 state matches:  ", state == session_state)
tok = token_endpoint(code, "printkaro", "pk-secret-91")
print("3 exchange code:  ", tok["token_type"], "token, scope", tok["scope"])
print("4 replay the code:", token_endpoint(code, "printkaro", "pk-secret-91"))
print("5 forged callback, state matches:", "attacker-state" == session_state)

Output (codes and tokens differ on every run):

1 browser lands on: https://printkaro.example/cb?code=GJ4ZKxzD&state=LmJUAXeA
2 state matches:   True
3 exchange code:   Bearer token, scope photos:read
4 replay the code: {'error': 'invalid_grant'}
5 forged callback, state matches: False

The token never appeared in a web address, the code didn't work twice, and the forged callback failed the state check.

Problem 4: redirect URI validation

The redirect_uri decides where the code goes, and it travels through the browser, so an attacker can change it. Every client registers its redirect URI in advance; the question is how strictly the server compares.

Demo 4: prefix matching vs exact matching

# Where may the authorization server send the code? Only to a REGISTERED redirect URI.
REGISTERED = "https://printkaro.example"

def prefix_match(uri): return uri.startswith(REGISTERED)       # the obvious check
def exact_match(uri):  return uri == REGISTERED                 # RFC 9700: exact string match

tests = ["https://printkaro.example",
         "https://printkaro.example.evil.example/cb",            # a DIFFERENT host!
         "https://printkaro.example/go?to=https://evil.example", # an open redirect page
         "https://evil.example/cb"]
for uri in tests:
    print(f"prefix: {prefix_match(uri)!s:5}  exact: {exact_match(uri)!s:5}  {uri}")

Output:

prefix: True   exact: True   https://printkaro.example
prefix: True   exact: False  https://printkaro.example.evil.example/cb
prefix: True   exact: False  https://printkaro.example/go?to=https://evil.example
prefix: False  exact: False  https://evil.example/cb
  • printkaro.example.evil.example is a different website that merely starts with the same letters.
  • /go?to=... is an open redirect: a page that forwards visitors anywhere it's told, so the code would be passed on to evil.example.

RFC 9700 (January 2025): authorization servers MUST utilize exact string matching for redirect URIs (the only exception is the port number of localhost URIs for native apps). If the redirect URI is wrong, the server must show an error on its own page and not redirect anywhere.

Problem 5: apps that can't keep a secret (PKCE)

Confidential client Public client
Where the code runs On the developer's server On the user's device (phone app, single-page web app, desktop app)
Can keep a client secret? Yes No: anyone can unpack the app and read it
Example PrintKaro's website backend PrintKaro's phone app

On a phone, a malicious app can register the same return address (like printkaro://cb), catch the authorization code, and, with no client secret required, swap it for a token. RFC 7636 calls this the authorization code interception attack.

The fix: PKCE ("pixie")

PKCE = Proof Key for Code Exchange, RFC 7636 (September 2015):

  1. For each login, the app makes a fresh random code_verifier and keeps it in memory.
  2. It computes code_challenge = BASE64URL(SHA256(code_verifier)) (the method called S256) and sends only the challenge in step 1.
  3. In step 4 it sends the verifier; the server hashes it and compares with the stored challenge.

A hash can't be reversed, so a thief who sees the challenge and steals the code still can't finish. RFC 9700: "Public clients MUST use PKCE", and it recommends PKCE for every client (it also protects against injected codes, like state does).

Demo 5: S256, checked against the RFC's own example

# PKCE: prove that whoever swaps the code is whoever started the login (RFC 7636, S256)
import base64, hashlib, secrets
def s256(verifier):
    return base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()

print("RFC 7636 example:", s256("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"))

pending = {}                                       # authorization server: code -> challenge
verifier = secrets.token_urlsafe(32)               # the app keeps this secret, in memory
pending["code-77"] = s256(verifier)                # only the HASH travels in step 1

def exchange(code, code_verifier):                 # token endpoint
    challenge = pending.get(code)
    if challenge is None or s256(code_verifier) != challenge: return "invalid_grant"
    del pending[code]; return "access_token issued"

print("malicious app, stolen code:", exchange("code-77", "i-guess-the-verifier"))
print("real app, with verifier:   ", exchange("code-77", verifier))

Output:

RFC 7636 example: E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
malicious app, stolen code: invalid_grant
real app, with verifier:    access_token issued

The first line reproduces the example in RFC 7636 Appendix B exactly: verifier dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk → challenge E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM.

Problem 6: no keyboard, no user

Real life OAuth 2.0 Who is present
A smart TV: typing a password with a remote is painful Device authorization flow (RFC 8628, August 2019) A user, but on a second device
A nightly backup job: no person is awake to click Allow Client credentials flow No user; the program acts as itself
A guard phoning the desk: "is pass 47 still valid?" Token introspection (RFC 7662) The resource server asks the authorization server

Demo 6: the device flow

The TV gets a device code (for itself) and a short user code (for you), plus a verification URI to visit on your phone. It then polls (asks repeatedly) the token endpoint every interval seconds. Until you approve, the answer is authorization_pending; if it polls too fast, slow_down (add 5 seconds to the interval).

# Device authorization flow (RFC 8628): a smart TV with no keyboard. Simulated locally.
approved = {"done": False}
def device_authorization():                    # TV asks the authorization server
    return {"device_code": "dv-5521", "user_code": "WDJB-MJHT",
            "verification_uri": "https://login.ravi.example/device", "interval": 5}

def token(device_code):                        # TV polls this every `interval` seconds
    return {"access_token": "at-tv-01"} if approved["done"] else {"error": "authorization_pending"}

d = device_authorization()
print(f"TV screen: visit {d['verification_uri']} and enter {d['user_code']}")
print("poll 1:", token(d["device_code"]))
approved["done"] = True                        # Neha types the code on her phone and approves
print("poll 2:", token(d["device_code"]))

Output:

TV screen: visit https://login.ravi.example/device and enter WDJB-MJHT
poll 1: {'error': 'authorization_pending'}
poll 2: {'access_token': 'at-tv-01'}

Because the user types a code shown by a device, attackers sometimes try to trick people into entering their code (device-code phishing). Only enter a code that your own device is showing you right now.

Demo 7: client credentials and introspection

# Client credentials flow: no user at all, a program acting as itself (machine to machine)
CLIENTS = {"nightly-backup": {"secret": "bk-8812", "scope": "photos:read"}}

def token(client_id, client_secret):
    c = CLIENTS.get(client_id)
    if not c or c["secret"] != client_secret: return {"error": "invalid_client"}
    return {"access_token": "at-bk-77", "scope": c["scope"], "expires_in": 600}

def introspect(token):                          # RFC 7662: "is this token still good?"
    return {"active": True, "client_id": "nightly-backup", "scope": "photos:read"} \
        if token == "at-bk-77" else {"active": False}

t = token("nightly-backup", "bk-8812")
print("backup job:", t["scope"], "| expires_in:", t["expires_in"])
print("introspect at-bk-77:  ", introspect("at-bk-77")["active"])
print("introspect at-made-up:", introspect("at-made-up")["active"])

Output:

backup job: photos:read | expires_in: 600
introspect at-bk-77:   True
introspect at-made-up: False

Use client credentials only when no user is involved, keep the secret on a server (never inside a public app), and give the client the narrowest scope. Introspection lets a resource server check opaque tokens (episode 31) and see revocations immediately.

Problem 7: deprecated grants and OAuth 2.1

A grant (grant type) is one of the ways a client obtains a token. Two shortcuts from 2012 are now deprecated (officially discouraged and on their way out):

Grant What it did Why it's bad RFC 9700 says Use instead
Implicit (response_type=token) Put the access token straight in the redirect URL, for browser apps without a server Token in the URL (history, logs, Referer); can't be sender-constrained Clients SHOULD NOT use it Authorization code + PKCE
Resource owner password credentials ("password grant") The app collected the user's password and sent it to /token Problem 1 again; exposes the password; breaks MFA MUST NOT be used Authorization code + PKCE (or device flow)

OAuth 2.1

OAuth 2.1 combines OAuth 2.0 (RFC 6749 and RFC 6750, bearer token usage) with a decade of security fixes (including RFC 9700) in one document. It keeps three grants, authorization code (with PKCE), client credentials and refresh token, and drops the implicit and password grants. As of 5 November 2026 it is still an IETF Internet-Draft (draft-ietf-oauth-v2-1, revision 17, dated 31 October 2026), not yet an RFC, but its rules are today's best practice.

The next problem

PrintKaro now wants a "Log in with Ravi Photos" button, and simply treats any valid access token as proof of who the user is. An access token was never meant for that: it says what an app may access, not who logged in, nor for which app. The fix is a token about the user, made for the app: OpenID Connect, with single sign-on and federation. Episode 33.

The whole chain

  1. Sharing a password → delegated authorization: four roles, an access token, scopes, consent.
  2. A token in a web address → the authorization code flow: one-time code on the front channel, token on the back channel.
  3. Forged callbacks → state; codes sent astray → exact redirect URI matching.
  4. Apps that can't keep a secret → public clients use PKCE (S256).
  5. A TV and a backup job → device flow and client credentials; checking opaque tokens → introspection.
  6. Old shortcuts → no implicit, no password grant; OAuth 2.1.

...and you just invented OAuth 2.0.

Common mistakes (and what they print)

Mistake What you see Why it's wrong Fix
Asking for the user's password PrintKaro deletes: 200 all photos deleted A password is full access OAuth with narrow scopes
Prefix-matching redirect URIs prefix: True exact: False https://printkaro.example.evil.example/cb Codes go to another host Exact string match
Public client without PKCE An intercepted code is swapped for a token Nothing proves who started the login PKCE with S256
No state (or PKCE) check on the callback A forged callback logs Neha into the attacker's account Login CSRF Check state, use PKCE
Codes that work twice A replayed code returns a second token Codes must be one-time Delete on first use (pop)
Over-broad scopes photos:read photos:write photos:delete for a print job Breach = full access Request the minimum
Parsing an error callback as if it had a code ValueError: not enough values to unpack (expected 2, got 1) ?error=access_denied has no code Check for error first; handle denial politely
Looking up an unknown code without .get KeyError: 'code-77' Untrusted input crashes the server .get(...) and answer invalid_grant
Client secret inside a phone app Anyone can unpack it Public clients can't keep secrets Treat as public client + PKCE
Implicit or password grant Tokens in URLs / passwords in apps Deprecated (RFC 9700) Code flow + PKCE

Mini project: Ravi's toy authorization server

A complete local flow for a public client (a phone app): exact redirect URIs, allowed scopes per client, consent (yes/no), one-time codes bound to the client and redirect URI, PKCE, and standard error codes.

# Ravi's toy authorization server: code flow + PKCE + state + exact redirect URIs + one-time codes + scopes
import base64, hashlib, secrets

def s256(v): return base64.urlsafe_b64encode(hashlib.sha256(v.encode()).digest()).rstrip(b"=").decode()

CLIENTS = {"printkaro-app": {"redirect": "printkaro://cb", "scopes": {"photos:read"}}}   # a public client
codes, tokens = {}, {}

def authorize(client_id, redirect_uri, scope, state, challenge, user_says_yes=True):
    c = CLIENTS.get(client_id)
    if c is None or redirect_uri != c["redirect"]: return "error: invalid redirect_uri (shown on the server's page)"
    if not set(scope.split()) <= c["scopes"]:      return f"{redirect_uri}?error=invalid_scope&state={state}"
    if not user_says_yes:                          return f"{redirect_uri}?error=access_denied&state={state}"
    code = secrets.token_urlsafe(8)
    codes[code] = {"client": client_id, "scope": scope, "challenge": challenge, "redirect": redirect_uri}
    return f"{redirect_uri}?code={code}&state={state}"

def token(code, client_id, redirect_uri, verifier):
    rec = codes.pop(code, None)                    # one use only
    if (rec is None or rec["client"] != client_id or rec["redirect"] != redirect_uri
            or s256(verifier) != rec["challenge"]):
        return {"error": "invalid_grant"}
    t = secrets.token_urlsafe(8); tokens[t] = rec["scope"]
    return {"access_token": t, "token_type": "Bearer", "expires_in": 600, "scope": rec["scope"]}

# --- the PrintKaro phone app ---
state, verifier = secrets.token_urlsafe(8), secrets.token_urlsafe(32)
back = authorize("printkaro-app", "printkaro://cb", "photos:read", state, s256(verifier))
params = dict(kv.split("=") for kv in back.split("?")[1].split("&"))
print("state ok:       ", params["state"] == state)
resp = token(params["code"], "printkaro-app", "printkaro://cb", verifier)
print("token issued:   ", resp["token_type"], resp["scope"], resp["expires_in"], "s")
print("code reused:    ", token(params["code"], "printkaro-app", "printkaro://cb", verifier))
print("evil redirect:  ", authorize("printkaro-app", "https://evil.example/cb", "photos:read", "s1", "c"))
print("too much scope: ", authorize("printkaro-app", "printkaro://cb", "photos:delete", "s2", "c"))
print("user said no:   ", authorize("printkaro-app", "printkaro://cb", "photos:read", "s3", "c", False))

Output:

state ok:        True
token issued:    Bearer photos:read 600 s
code reused:     {'error': 'invalid_grant'}
evil redirect:   error: invalid redirect_uri (shown on the server's page)
too much scope:  printkaro://cb?error=invalid_scope&state=s2
user said no:    printkaro://cb?error=access_denied&state=s3

Note the two kinds of error: a bad redirect URI is shown on the authorization server's own page (never redirect to an unverified address), while other errors (invalid_scope, access_denied) are sent back to the registered redirect URI with the state.

Ideas to extend it: add refresh tokens with rotation (episode 31); add an /introspect function; let the user see and revoke every app with access.

Practice

1. A write scope. Extend Demo 2 with photos:write that adds a photo. Give PrintKaro read and write, but still not delete.

Solution
import secrets
photos = ["goa1.jpg", "goa2.jpg", "diwali.jpg"]
tokens = {}
def issue(client, scopes):
    t = secrets.token_urlsafe(12); tokens[t] = {"client": client, "scope": scopes, "active": True}
    return t
def photo_api(token, action):
    rec = tokens.get(token)
    if not rec or not rec["active"]: return "401 invalid_token"
    if f"photos:{action}" not in rec["scope"]: return "403 insufficient_scope"
    if action == "write": photos.append("album-cover.jpg"); return f"200 {photos}"
    return f"200 {photos}"
t = issue("printkaro", {"photos:read", "photos:write"})
print("write:  ", photo_api(t, "write"))
print("delete: ", photo_api(t, "delete"))
write:   200 ['goa1.jpg', 'goa2.jpg', 'diwali.jpg', 'album-cover.jpg']
delete:  403 insufficient_scope

2. A wrong client secret. Make the token endpoint in Demo 3 answer invalid_client for a wrong secret, and keep the code usable by the real client.

Solution
import secrets
codes = {"c-1": {"client": "printkaro", "scope": "photos:read"}}
def token_endpoint(code, client_id, client_secret):
    rec = codes.get(code)
    if rec is None or rec["client"] != client_id or client_secret != "pk-secret-91":
        return {"error": "invalid_client" if rec and client_secret != "pk-secret-91" else "invalid_grant"}
    codes.pop(code)
    return {"access_token": secrets.token_urlsafe(8), "token_type": "Bearer", "scope": rec["scope"]}
print("wrong secret:", token_endpoint("c-1", "printkaro", "guess-123"))
print("right secret:", "access_token" in token_endpoint("c-1", "printkaro", "pk-secret-91"))
wrong secret: {'error': 'invalid_client'}
right secret: True

invalid_client = the app failed to authenticate; invalid_grant = the code (or refresh token) is bad, expired or already used.

3. slow_down in the device flow. Answer slow_down when the TV polls again within 5 seconds.

Solution
approved = {"done": False}
last_poll = {"t": None}
def token(device_code, now):
    if last_poll["t"] is not None and now - last_poll["t"] < 5:
        last_poll["t"] = now; return {"error": "slow_down"}
    last_poll["t"] = now
    return {"access_token": "at-tv-01"} if approved["done"] else {"error": "authorization_pending"}
print("t=0 :", token("dv-5521", 0))
print("t=2 :", token("dv-5521", 2))      # polled too fast
approved["done"] = True
print("t=12:", token("dv-5521", 12))
t=0 : {'error': 'authorization_pending'}
t=2 : {'error': 'slow_down'}
t=12: {'access_token': 'at-tv-01'}

4. Pick the flow. (a) A command-line tool on a developer's laptop that reads their own GitHub-style repositories. (b) A billing service that calls the invoices API every hour. (c) A single-page web app with no server. (d) A smart speaker.

Solution

(a) Authorization code + PKCE with a localhost redirect (or the device flow): a user is present, and a CLI is a public client. (b) Client credentials: no user. (c) Authorization code + PKCE (never implicit); ideally with a small backend that keeps tokens out of the browser (episode 31). (d) Device authorization flow.

5. Spot the bugs. A client builds .../authorize?response_type=token&client_id=shop&redirect_uri=https://shop.example&scope=*. List three problems.

Solution

response_type=token is the deprecated implicit grant (token in the URL); no state and no PKCE code_challenge (CSRF and code injection); scope=* asks for everything instead of the minimum. Also check that the server matches https://shop.example exactly.

Quick quiz

A smart speaker in Neha's kitchen needs access to her music playlists. It has no keyboard and no browser. Which flow fits?

  • A: client credentials
  • B: device authorization flow
  • C: password grant
  • D: implicit grant
Answer

B, the device authorization flow. It's Neha's data, so she must approve; the speaker shows (or says) a code and she approves on her phone. Client credentials has no user, and the password and implicit grants are deprecated.

Interview questions

  1. What problem does OAuth 2.0 solve? Delegated authorization: letting an app access a user's resources with limited, revocable permission instead of the user's password.
  2. Name the four OAuth roles. Resource owner (user), client (app), authorization server (issues tokens), resource server (API holding the data).
  3. Why does the authorization code flow use a code instead of returning the token directly? URLs leak (history, logs, Referer); the one-time code is swapped for the token on the back channel, optionally authenticated with the client secret.
  4. What is the state parameter for? It binds the callback to the browser session that started the login, preventing CSRF / code injection.
  5. Why must redirect URIs match exactly? Prefix or pattern matching lets codes be sent to look-alike hosts or open redirects; RFC 9700 requires exact string matching.
  6. Public vs confidential clients? Confidential clients run on servers and can keep a secret; public clients (mobile, SPA, desktop) can't.
  7. How does PKCE work? The client sends code_challenge = BASE64URL(SHA256(code_verifier)) with the authorization request and the verifier with the token request; the server checks they match, so an intercepted code is useless.
  8. When do you use client credentials? Machine-to-machine calls with no user; the client authenticates as itself and gets a token for its own access.
  9. What is the device authorization flow? For input-constrained devices: the device shows a user code and a verification URI, the user approves on another device, and the device polls the token endpoint.
  10. Why are the implicit and password grants deprecated? Implicit puts tokens in URLs; the password grant exposes the user's password to the client and breaks MFA. RFC 9700: SHOULD NOT / MUST NOT.
  11. What is token introspection? An authorization-server endpoint (RFC 7662) where a resource server asks whether a token is active and what it allows.
  12. Is OAuth an authentication protocol? No. It's for authorization; authentication on top of it is OpenID Connect (episode 33).

Glossary

Term Meaning in plain words Example
OAuth 2.0 A framework for delegated authorization (RFC 6749, October 2012) "Allow PrintKaro to view your photos?"
Delegated authorization Letting an app act for you with limited rights A valet key
Resource owner The user who owns the data and decides Neha
Client The app asking for access (never the person) PrintKaro
Authorization server Checks who the user is, asks consent, issues tokens login.ravi.example
Resource server The API that holds the data and checks tokens Ravi Photos API
Access token A limited, expiring, revocable permission photos:read token
Scope A named permission the client asks for photos:read
Consent The user approving exactly the requested scopes Clicking Allow
Consent screen The page that asks the user to approve "PrintKaro wants to..."
401 Unauthorized Credentials missing or invalid Revoked token
403 Forbidden Known caller, not allowed Missing scope
Grant (grant type) A way for a client to obtain a token Authorization code
Authorization code flow Code via the browser, token via a direct server call Demo 3
Authorization endpoint Where the browser is sent to log in and consent /authorize
Token endpoint Where codes (or credentials) are exchanged for tokens /token
Authorization code A short-lived, one-time code swapped for a token code=BY1k...
Front channel Messages carried through the user's browser Redirects
Back channel Direct server-to-server calls POST /token
Client ID The public name of a registered app printkaro
Client secret A password for the app itself (confidential clients only) pk-secret-91
Redirect URI Where the browser is sent back with the code https://printkaro.example/cb
Exact string matching Accepting only the registered redirect URI, character for character RFC 9700 rule
Open redirect A page that forwards visitors to any address it's given /go?to=...
Referer header Tells the next site which page you came from Leaks URLs
State parameter A random value that ties the callback to the browser session that started it state=K71G...
CSRF Cross-site request forgery: another site makes your browser send a request Login CSRF
Public client An app that can't keep a secret Phone app, SPA
Confidential client An app on a server that can keep a secret Website backend
Authorization code interception A malicious app catching another app's code Same custom URL scheme
PKCE Proof Key for Code Exchange (RFC 7636): a per-login secret proving who started the flow Demo 5
Code verifier The random per-login secret kept by the app secrets.token_urlsafe(32)
Code challenge BASE64URL(SHA256(verifier)), sent in step 1 E9Melhoa2...
S256 The SHA-256 PKCE method code_challenge_method=S256
Client credentials flow A program gets a token as itself, no user Nightly backup job
Device authorization flow Approve on a second device by entering a code (RFC 8628) Smart TV
Device code / user code The device's own code / the short code the user types WDJB-MJHT
Verification URI Where the user enters the user code login.ravi.example/device
Polling Asking the same question repeatedly at an interval Every 5 s
authorization_pending / slow_down Keep waiting / poll more slowly Device flow answers
Token introspection Asking the authorization server whether a token is active (RFC 7662) {"active": true}
Implicit grant Deprecated: token returned in the redirect URL response_type=token
Password grant (ROPC) Deprecated: the app collects the user's password grant_type=password
Deprecated Officially discouraged and being phased out Implicit grant
RFC 9700 OAuth 2.0 Security Best Current Practice (January 2025) "Public clients MUST use PKCE"
OAuth 2.1 OAuth 2.0 + security best practice in one document (still a draft) draft-ietf-oauth-v2-1
invalid_grant / invalid_client Bad code or refresh token / app failed to authenticate Token endpoint errors

Summary

  • Never give an app your password: it's all-or-nothing and can't be revoked per app.
  • OAuth 2.0 (RFC 6749, 2012) gives a client a limited, revocable access token with scopes the resource owner consented to, issued by the authorization server and checked by the resource server.
  • Use the authorization code flow: a one-time code on the front channel, the token on the back channel, a state value against CSRF, and exactly matched redirect URIs (RFC 9700).
  • Public clients can't keep secrets: use PKCE (RFC 7636, S256), and in practice use it everywhere.
  • Device flow (RFC 8628) for TVs and speakers, client credentials for programs with no user, introspection (RFC 7662) to check opaque tokens.
  • The implicit and password grants are deprecated (RFC 9700); OAuth 2.1 (still an IETF draft, revision 17, 31 Oct 2026) drops them.

Next episode: OpenID Connect, SSO and federation: authentication vs authorization, ID tokens, nonce, UserInfo, discovery, single sign-on, IdP and SP, SAML 2.0, SCIM provisioning and single logout.

Sources: RFC 6749 "The OAuth 2.0 Authorization Framework" (IETF, October 2012); RFC 7636 "Proof Key for Code Exchange by OAuth Public Clients" (September 2015); RFC 8628 "OAuth 2.0 Device Authorization Grant" (August 2019); oauth.com "Map of OAuth 2.0 Specs" (RFC 6750, RFC 7662); RFC 9700 "Best Current Practice for OAuth 2.0 Security" (January 2025); IETF datatracker, draft-ietf-oauth-v2-1 (revision 17, 31 Oct 2026). Code outputs from Python 3.13. Fetched 5 Nov 2026.