OAuth 2.0 and OpenID Connect
"Sign in with Google", "Allow this app to read your calendar", one account for every app of a company: all of these are OAuth 2.0 and OpenID Connect (OIDC). OAuth answers delegation: how can an application act on a user's behalf at an API without ever learning the user's password? OIDC, built on top, answers authentication: how can an application learn reliably who the user is? The protocols are flexible, with several flows, token types and optional parameters, and most real-world OAuth vulnerabilities come from picking the wrong flow or skipping one of the checks. This lesson lays out the roles and the authorization code flow and runs a toy authorization server in Python; the next lesson adds PKCE through ExcelTAD's own TAD sign-in, and the one after breaks things.
Definitions
- Roles (RFC 6749): the resource owner (the user), the client (the application), the authorization server (AS, issues tokens; in OIDC also called the OpenID Provider, OP), the resource server (the API that accepts access tokens).
- Confidential client: can keep a secret (a backend). Public client: can't (a single-page app, a mobile app); it authenticates with PKCE instead of a secret.
- Authorization code flow: the browser is sent to the AS's
/authorizeendpoint; the user signs in there; the AS redirects back to the client's registeredredirect_uriwith a short-lived, single-use code; the client exchanges the code at the/tokenendpoint (a direct request, not through the browser) for tokens. - Tokens: an access token (for APIs, short-lived, opaque or a JWT, its audience is the API), a refresh token (for new access tokens without the user, long-lived, ideally rotating), and in OIDC an ID token (a JWT for the client describing the sign-in:
iss,sub,aud= client id,exp,iat,nonce,auth_time,amr). - Scopes: what the client asks for (
openid profile email offline_access orders:read). state: a random value the client sends to/authorizeand expects back, binding the response to this browser's request (CSRF protection for the redirect).nonce(OIDC): a random value echoed inside the ID token, binding the token to the request (replay protection).- Discovery (OIDC):
/.well-known/openid-configurationlists the endpoints and the JWKS URL with the AS's public signing keys. - Current guidance: RFC 9700 (Best Current Practice for OAuth 2.0 Security, 2025) and the OAuth 2.1 draft: authorization code with PKCE for every client, no implicit flow, no password grant, exact
redirect_urimatching, refresh-token rotation or sender-constraining for public clients.
The authorization code flow
Two design choices carry the security. Tokens never travel through the browser's address bar (only the code does, and it is single-use, short-lived and bound to the client and redirect_uri), and the code exchange in step 5 is a direct request that the AS can authenticate (client secret or PKCE).
A toy authorization server
The example implements steps 2 to 6 for a confidential client in memory: no network, a fixed "random" generator so the output is stable (real servers use secrets), and the checks RFC 6749 and RFC 9700 require at the token endpoint.
import hashlib, hmac, itertools, json
counter = itertools.count(1)
def rnd(prefix): return f"{prefix}-{next(counter):04d}" # stand-in for secrets.token_urlsafe(32)
CLIENTS = {"shop-web": {"secret_hash": hashlib.sha256(b"lab-client-secret").hexdigest(),
"redirect_uris": {"https://shop.lab.test/callback"}}}
CODES = {}
def authorize(client_id, redirect_uri, scope, state, nonce, user):
c = CLIENTS.get(client_id)
if not c or redirect_uri not in c["redirect_uris"]: # exact match, before redirecting anywhere
return "400 invalid client or redirect_uri (shown on the AS, never redirected)"
code = rnd("code")
CODES[code] = {"client_id": client_id, "redirect_uri": redirect_uri, "user": user,
"scope": scope, "nonce": nonce, "used": False, "expires": 60}
return f"302 {redirect_uri}?code={code}&state={state}"
def token(client_id, client_secret, code, redirect_uri):
c, entry = CLIENTS.get(client_id), CODES.get(code)
if not c or not hmac.compare_digest(hashlib.sha256(client_secret.encode()).hexdigest(), c["secret_hash"]):
return {"error": "invalid_client"}
if not entry or entry["client_id"] != client_id or entry["redirect_uri"] != redirect_uri:
return {"error": "invalid_grant"}
if entry["used"]:
return {"error": "invalid_grant", "note": "code reuse: revoke tokens issued from it"}
entry["used"] = True
id_claims = {"iss": "https://auth.lab.test", "sub": entry["user"], "aud": client_id, "nonce": entry["nonce"]}
return {"access_token": rnd("at"), "token_type": "Bearer", "expires_in": 900,
"refresh_token": rnd("rt"), "id_token(claims)": id_claims}
print(authorize("shop-web", "https://shop.lab.test/callback", "openid orders:read", "st-81", "nn-17", "user-42"))
print(json.dumps(token("shop-web", "lab-client-secret", "code-0001", "https://shop.lab.test/callback")))
print("same code again:", token("shop-web", "lab-client-secret", "code-0001", "https://shop.lab.test/callback"))
print("wrong secret: ", token("shop-web", "guess", "code-0001", "https://shop.lab.test/callback"))
print(authorize("shop-web", "https://shop.lab.test.evil.example/callback", "openid", "st-82", "nn-18", "user-42"))302 https://shop.lab.test/callback?code=code-0001&state=st-81
{"access_token": "at-0002", "token_type": "Bearer", "expires_in": 900, "refresh_token": "rt-0003", "id_token(claims)": {"iss": "https://auth.lab.test", "sub": "user-42", "aud": "shop-web", "nonce": "nn-17"}}
same code again: {'error': 'invalid_grant', 'note': 'code reuse: revoke tokens issued from it'}
wrong secret: {'error': 'invalid_client'}
400 invalid client or redirect_uri (shown on the AS, never redirected)
The client, back on its callback, still has work to do before it trusts anything: compare state with the one it stored, and validate the ID token (signature from the JWKS, iss, aud equal to its client id, exp, and nonce equal to the one it stored). Only then is sub the signed-in user. The user is identified by sub (unique per issuer), never by e-mail, which can change and be reassigned.
How OAuth/OIDC integrations are tested (detection)
- Map the flow with an intercepting proxy: which
response_type(codeis the only good answer for new apps), is therestate,nonce,code_challenge? Are tokens ever in a URL fragment or query? - Tamper: change
redirect_uri(another path, subdomain, scheme, extra parameters); drop or reusestate; replay a code; exchange a code with another client's credentials; send an ID token from another client (aud) or an old one (nonce,exp). - Logs on the AS:
invalid_grantfor reused codes (possible interception), redirect URI mismatches, refresh-token reuse (TAD revokes the whole session on reuse, see the next lesson).
How it is done right
- Authorization code flow with PKCE for every client; no implicit or password grant.
- Register exact redirect URIs; compare them as exact strings.
stateandnoncefrom a CSPRNG, stored per request, checked on return; or PKCE plus theissresponse parameter (RFC 9207) against mix-up attacks.- Validate ID tokens fully; use access tokens only at APIs (they are not proof of identity for the client); request the fewest scopes.
- Short-lived access tokens, rotating refresh tokens, revocation and logout handled (OIDC logout).
Pitfalls
- Using OAuth access tokens as login proof ("if I can call
/userinfo, the user is who the token says"): a token issued to another app for the same user would also work. Use the ID token, whoseaudis you. - Account linking by e-mail across providers: an attacker who registers the victim's e-mail at a provider that doesn't verify it gets the victim's account.
- Treating the AS's login page as "just a page": it must not be frameable (clickjacking of consent).
Practice
1. Why is the code exchanged in a direct request rather than returning tokens in the redirect?
The redirect passes through the browser: its URL can leak through history, logs, Referer and browser extensions. A single-use code that is useless without the client's secret or PKCE verifier limits the damage of a leak; tokens in the URL (the old implicit flow) would be usable directly.
2. Which ID token claim tells the client the token was issued for it, and what happens if it is not checked?
aud, which must contain the client's own client_id. Without the check, an ID token obtained by any other app at the same provider (for example a malicious app the user signed in to) could be replayed to log in as that user.
Test yourself
Which OAuth role issues tokens?
- Resource owner
- Client
- Authorization server
- Resource server
What does OIDC add to OAuth 2.0?
- Refresh tokens
- Authentication: the ID token, nonce, discovery and userinfo
- Scopes
- The client secret
In the toy AS, what happened to the second exchange of the same code?
- It returned new tokens
- invalid_grant: codes are single-use, and reuse signals interception
- invalid_client
- The AS crashed
Which identifier should a client use as the stable user key?
- name
- sub (with iss)
- access_token