Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 30 min · revision 2

Federating an App with a Lab Identity Provider

Run Dex v2.46.0 as a real OpenID Connect identity provider with a WebAuthn passkey step, build a Python relying party that uses the authorization code flow with PKCE, state and nonce, validate the ID token against the IdP's keys, and prove with negative tests that tampered, misdirected, replayed and phished logins are rejected.

Contentsand lesson path

What you will learn

  • Configure phishing-resistant MFA and single sign-on federation (OIDC or SAML) for an application in a lab identity provider and explain each trust relationship.

01. Goal and setup

You federate a small web app with a real identity provider (IdP): Dex v2.46.0, an open-source OpenID Connect (OIDC) provider whose v2.46 release added a WebAuthn passkey step. The app, the relying party (RP), is about 100 lines of Python. A script plays the browser: it keeps cookies, follows redirects, posts Dex's login form and answers the passkey challenge with a software authenticator, so every step prints real output. Then you attack each trust relationship and confirm that every attack is rejected.

You need: Docker with the image ghcr.io/dexidp/dex:v2.46.0, uv for a Python 3.12 environment, and curl. The packages are pinned: requests 2.34.2, PyJWT[crypto] 2.15.1, cryptography 50.0.2 and cbor2 6.3.0. Dex listens on 127.0.0.1:5590 and the RP on 127.0.0.1:8090. Every secret here is a lab value; never reuse it. Run every block in the same terminal: later blocks use the $DEX variable and the environment that earlier blocks set.

Project layout at the end of the lab
idp-lab/
├── dex/config.yaml   step 1: the IdP: client, user, passkey MFA
├── oidc_check.py     step 2: ID token validation
├── rp.py             step 2: the relying party on 127.0.0.1:8090
├── softkey.py        step 3: software passkey and browser rules
├── browser.py        step 3: drives the login like a browser
├── show_claims.py    step 4: prints the claims of the last token
└── attacks.py        step 5: negative tests
Terminal
mkdir -p idp-lab/dex && cd idp-lab
uv venv --python 3.12 && source .venv/bin/activate
uv pip install "requests==2.34.2" "PyJWT[crypto]==2.15.1" \
  "cryptography==50.0.2" "cbor2==6.3.0"
export DEX=idp-lab-dex   # container name used in every docker command

02. Step 1: Start the lab identity provider

Save this as dex/config.yaml. It defines one user, two apps (clients) and a WebAuthn step that every client must pass after the password. The issuer uses localhost, not 127.0.0.1, because WebAuthn accepts only domain names as RP IDs, and browsers treat http://localhost as a secure context. The hash is a bcrypt hash of the lab password correct-horse-lab-7; htpasswd -bnBC 10 "" <password> makes your own.

YAML · idp-lab/dex/config.yaml
# Lab identity provider: Dex v2.46.0. Lab-only secrets, never reuse them.
issuer: http://localhost:5590/dex
storage:
  type: memory            # everything is lost when the container stops
web:
  http: 0.0.0.0:5590      # inside the container; published on 127.0.0.1 only
logger:
  level: info
  format: text
oauth2:
  skipApprovalScreen: true
  pkce:
    enforce: true                         # refuse code flows without PKCE
    codeChallengeMethodsSupported: [S256] # no "plain"
sessions:
  absoluteLifetime: 8h
  validIfNotUsedFor: 1h
mfa:
  authenticators:
    - id: lab-passkey
      type: WebAuthn
      config:
        rpDisplayName: Lab IdP
        rpID: localhost
        rpOrigins: ["http://localhost:5590"]
        attestationPreference: none
  defaultMFAChain: [lab-passkey]          # every client needs the passkey step
enablePasswordDB: true
staticPasswords:
  - email: [email protected]
    username: ana
    userID: 6f1c2a9e-0b7d-4c55-9a1e-2b3c4d5e6f70
    hash: "$2b$10$lNMA956tezveFa8XUkxCA.qOBqv8QUgvbZxb7d4ret.dbGnCkCFsG"
staticClients:
  - id: notes-app
    name: Notes App
    secret: notes-app-lab-secret
    redirectURIs: ["http://127.0.0.1:8090/callback"]
  - id: reports-app
    name: Reports App
    secret: reports-app-lab-secret
    redirectURIs: ["http://127.0.0.1:8091/callback"]
Terminal
docker run -d --name "$DEX" -p 127.0.0.1:5590:5590 \
  -e DEX_SESSIONS_ENABLED=true \
  -v "$PWD/dex/config.yaml:/etc/dex/config.yaml:ro" \
  ghcr.io/dexidp/dex:v2.46.0 dex serve /etc/dex/config.yaml
sleep 3
docker logs "$DEX" 2>&1 | grep -E "MFA authenticator|sessions feature|listening"
curl -s http://localhost:5590/dex/.well-known/openid-configuration \
  | python -m json.tool \
  | grep -E '"(issuer|authorization_endpoint|token_endpoint|jwks_uri)"|"S256"'
Illustrative output (the container ID and times differ)
<container ID: 64 hexadecimal characters>
time=<time> level=INFO msg="MFA authenticator configured" id=lab-passkey type=WebAuthn
time=<time> level=INFO msg="sessions feature flag is enabled"
time=<time> level=INFO msg="listening on" server=http address=0.0.0.0:5590
Expected output
    "issuer": "http://localhost:5590/dex",
    "authorization_endpoint": "http://localhost:5590/dex/auth",
    "token_endpoint": "http://localhost:5590/dex/token",
    "jwks_uri": "http://localhost:5590/dex/keys",
        "S256"

The discovery document tells the RP where the endpoints and signing keys are. jwks_uri serves the public keys (a JSON Web Key Set, JWKS). Dex rotates its key every six hours by default, so the RP looks keys up by kid (key ID) instead of hard-coding one. Only S256 is offered for PKCE, and pkce.enforce: true refuses code flows without it, as RFC 9700, the OAuth 2.0 Security Best Current Practice, recommends.

03. Step 2: Build and start the relying party

oidc_check.py makes the ID token checks of OpenID Connect Core 1.0 section 3.1.3.7: a signature from the issuer's JWKS, iss exactly equal to the configured issuer, aud containing this client, exp in the future, and this login's nonce. It fixes the algorithm to RS256, so a token cannot pick its own.

Python · idp-lab/oidc_check.py
"""ID token validation for the lab RP (OIDC Core 1.0, section 3.1.3.7)."""
import jwt  # PyJWT

ISSUER = "http://localhost:5590/dex"


class TokenRejected(Exception):
    """The ID token failed one of the checks; the message says which."""


_jwks = jwt.PyJWKClient(ISSUER + "/keys", cache_keys=True)


def validate_id_token(token: str, *, audience: str, nonce: str,
                      issuer: str = ISSUER) -> dict:
    try:
        key = _jwks.get_signing_key_from_jwt(token)  # picks the key by "kid"
        claims = jwt.decode(
            token, key.key, algorithms=["RS256"],  # never trust the token's "alg"
            audience=audience, issuer=issuer, leeway=30,
            options={"require": ["iss", "sub", "aud", "exp", "iat", "nonce"]})
    except jwt.PyJWTError as exc:
        raise TokenRejected(f"{type(exc).__name__}: {exc}") from None
    if claims["nonce"] != nonce:
        raise TokenRejected("nonce mismatch: token was not minted for this login")
    return claims

rp.py is the app. /login creates and remembers three random values: state ties the callback to this browser (CSRF protection), nonce lets the RP recognise its own ID token, and the PKCE code_verifier, whose SHA-256 hash goes to Dex as code_challenge. /callback checks state, redeems the code with the verifier and client secret, and validates the token. /admin is a high-assurance page for step 7.

Python · idp-lab/rp.py
"""Lab relying party: OIDC authorization code flow with PKCE, state and nonce."""
import base64
import hashlib
import json
import os
import secrets
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlencode, urlsplit

import requests

from oidc_check import ISSUER, TokenRejected, validate_id_token

CLIENT_ID = "notes-app"
CLIENT_SECRET = os.environ["RP_CLIENT_SECRET"]
REDIRECT_URI = "http://127.0.0.1:8090/callback"
META = requests.get(ISSUER + "/.well-known/openid-configuration", timeout=5).json()
assert META["issuer"] == ISSUER, "discovery issuer must equal the configured issuer"

PENDING: dict[str, dict] = {}   # state -> nonce and PKCE verifier, used once
SESSIONS: dict[str, dict] = {}  # RP session id -> validated ID token claims
STRONG_ACR = {"phr", "phrh"}    # OpenID EAP ACR values: phishing-resistant


def b64url(raw: bytes) -> str:
    return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()


class RP(BaseHTTPRequestHandler):
    def reply(self, status: int, text: str, headers: dict | None = None) -> None:
        self.send_response(status)
        for name, value in (headers or {}).items():
            self.send_header(name, value)
        self.send_header("Content-Type", "text/plain")
        self.end_headers()
        self.wfile.write(text.encode())

    def cookie(self, name: str) -> str | None:
        jar = SimpleCookie(self.headers.get("Cookie", ""))
        return jar[name].value if name in jar else None

    def do_GET(self) -> None:
        url = urlsplit(self.path)
        q = {k: v[0] for k, v in parse_qs(url.query).items()}
        route = {"/login": self.login, "/callback": self.callback,
                 "/admin": self.admin}.get(url.path)
        if route is None:
            self.reply(404, "not found")
        else:
            route(q)

    def login(self, q: dict) -> None:
        state, nonce = secrets.token_urlsafe(16), secrets.token_urlsafe(16)
        verifier = secrets.token_urlsafe(48)
        PENDING[state] = {"nonce": nonce, "verifier": verifier}
        challenge = b64url(hashlib.sha256(verifier.encode()).digest())
        query = urlencode({
            "response_type": "code", "client_id": CLIENT_ID,
            "redirect_uri": REDIRECT_URI, "scope": "openid email profile",
            "state": state, "nonce": nonce,
            "code_challenge": challenge, "code_challenge_method": "S256"})
        self.reply(302, "", {"Location": META["authorization_endpoint"] + "?" + query,
                             "Set-Cookie": f"rp_state={state}; HttpOnly; Path=/"})

    def callback(self, q: dict) -> None:
        state = q.get("state", "")
        if not state or state != self.cookie("rp_state"):
            self.reply(400, "rejected: state does not match this browser (CSRF?)")
            return
        if state not in PENDING:
            self.reply(400, "rejected: state already used or unknown (replay?)")
            return
        login = PENDING.pop(state)                 # one use only
        token = requests.post(META["token_endpoint"], timeout=5,
                              auth=(CLIENT_ID, CLIENT_SECRET), data={
                                  "grant_type": "authorization_code",
                                  "code": q.get("code", ""),
                                  "redirect_uri": REDIRECT_URI,
                                  "code_verifier": login["verifier"]}).json()
        if "id_token" not in token:
            self.reply(400, f"rejected by IdP at token endpoint: {token}")
            return
        try:
            claims = validate_id_token(token["id_token"], audience=CLIENT_ID,
                                       nonce=login["nonce"])
        except TokenRejected as exc:
            self.reply(400, f"rejected ID token: {exc}")
            return
        with open("last_id_token.txt", "w") as fh:  # lab only: input for attacks.py
            fh.write(token["id_token"])
        sid = secrets.token_urlsafe(24)
        SESSIONS[sid] = claims
        seen = {k: claims.get(k) for k in ("email", "acr", "amr")}
        self.reply(200, f"signed in: {json.dumps(seen)}",
                   {"Set-Cookie": f"rp_sid={sid}; HttpOnly; Path=/"})

    def admin(self, q: dict) -> None:
        claims = SESSIONS.get(self.cookie("rp_sid") or "")
        if claims is None:
            self.reply(401, "no session")
        elif claims.get("acr") in STRONG_ACR or "hwk" in claims.get("amr", []):
            self.reply(200, f"admin area for {claims['email']}")
        else:
            self.reply(403, "step-up required: no acr/amr proof of "
                            "phishing-resistant MFA")

    def log_message(self, fmt: str, *args: object) -> None:
        print("rp:", fmt % args, flush=True)


if __name__ == "__main__":
    server = ThreadingHTTPServer(("127.0.0.1", 8090), RP)  # port is bound here
    print("RP on http://127.0.0.1:8090 trusting issuer", ISSUER, flush=True)
    server.serve_forever()
Terminal
export RP_CLIENT_SECRET=notes-app-lab-secret   # lab value from dex/config.yaml
python rp.py > rp.log 2>&1 &
RP_PID=$!
for i in $(seq 20); do grep -qs '^RP on' rp.log && break; sleep 0.5; done
cat rp.log
Expected output
RP on http://127.0.0.1:8090 trusting issuer http://localhost:5590/dex

04. Step 3: Sign in and register a passkey

softkey.py is a software passkey, a teaching model like lesson 2's: an ES256 key pair per RP ID, the public key encoded in CBOR for registration, and a signature over authenticatorData plus the hash of clientDataJSON. It also applies the browser rule that a page may only use an RP ID matching its host. The verifier is real: Dex checks every byte with the go-webauthn library.

browser.py follows the login through the RP, Dex's password form and the passkey page. The first time, Dex finds no passkey for ana and asks her to register one, so here a password alone can enrol a passkey. Production systems should enrol through a verified process.

Python · idp-lab/softkey.py
"""A software passkey plus the browser rules around it (teaching model, ES256).

Real browsers and authenticators do much more (attestation, PIN/biometrics,
hybrid transport). Do not use this outside the lab.
"""
import base64
import hashlib
import json
import os
import struct
from urllib.parse import urlsplit

import cbor2
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec

UP, UV, AT = 0x01, 0x04, 0x40  # authenticatorData flag bits


def b64u(raw: bytes) -> str:
    return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()


def unb64u(text: str) -> bytes:
    return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))


class SecurityError(Exception):
    """What a browser raises when a page asks for another site's RP ID."""


class SoftKey:
    def __init__(self, path: str = "softkey.json") -> None:
        self.path = path
        self.creds = json.load(open(path)) if os.path.exists(path) else {}

    def _save(self) -> None:
        json.dump(self.creds, open(self.path, "w"), indent=1)

    @staticmethod
    def browser_check(rp_id: str, page_origin: str) -> None:
        host = urlsplit(page_origin).hostname or ""
        if host != rp_id and not host.endswith("." + rp_id):
            raise SecurityError(f"page {page_origin} may not use RP ID {rp_id!r}")

    @staticmethod
    def client_data(kind: str, challenge: str, origin: str) -> bytes:
        return json.dumps({"type": kind, "challenge": challenge, "origin": origin,
                           "crossOrigin": False}, separators=(",", ":")).encode()

    def create(self, options: dict, page_origin: str) -> dict:
        pk = options["publicKey"]
        rp_id = pk["rp"]["id"]
        self.browser_check(rp_id, page_origin)
        key = ec.generate_private_key(ec.SECP256R1())
        cred_id = os.urandom(16)
        nums = key.public_key().public_numbers()
        cose = cbor2.dumps({1: 2, 3: -7, -1: 1, -2: nums.x.to_bytes(32, "big"),
                            -3: nums.y.to_bytes(32, "big")})
        auth_data = (hashlib.sha256(rp_id.encode()).digest()
                     + bytes([UP | UV | AT]) + struct.pack(">I", 0)
                     + bytes(16) + struct.pack(">H", len(cred_id)) + cred_id + cose)
        cdata = self.client_data("webauthn.create", pk["challenge"], page_origin)
        att = cbor2.dumps({"fmt": "none", "attStmt": {}, "authData": auth_data})
        self.creds[rp_id] = {"id": b64u(cred_id), "counter": 0,
                             "user": pk["user"]["id"],
                             "pem": key.private_bytes(
                                 serialization.Encoding.PEM,
                                 serialization.PrivateFormat.PKCS8,
                                 serialization.NoEncryption()).decode()}
        self._save()
        return {"id": b64u(cred_id), "rawId": b64u(cred_id), "type": "public-key",
                "response": {"attestationObject": b64u(att),
                             "clientDataJSON": b64u(cdata)}}

    def get(self, options: dict, page_origin: str, *, honest_browser=True) -> dict:
        pk = options["publicKey"]
        rp_id = pk["rpId"]
        if honest_browser:                 # a phishing kit may bypass this check
            self.browser_check(rp_id, page_origin)
        cred = self.creds[rp_id]
        cred["counter"] += 1
        self._save()
        auth_data = (hashlib.sha256(rp_id.encode()).digest() + bytes([UP | UV])
                     + struct.pack(">I", cred["counter"]))
        cdata = self.client_data("webauthn.get", pk["challenge"], page_origin)
        key = serialization.load_pem_private_key(cred["pem"].encode(), None)
        sig = key.sign(auth_data + hashlib.sha256(cdata).digest(),
                       ec.ECDSA(hashes.SHA256()))
        return {"id": cred["id"], "rawId": cred["id"], "type": "public-key",
                "response": {"authenticatorData": b64u(auth_data),
                             "clientDataJSON": b64u(cdata), "signature": b64u(sig),
                             "userHandle": cred["user"]}}
Python · idp-lab/browser.py
"""Drives the login like a browser would: cookies, redirects, forms, passkey."""
import re
import sys
from urllib.parse import urljoin, urlsplit

import requests

from softkey import SoftKey

RP = "http://127.0.0.1:8090"
IDP_ORIGIN = "http://localhost:5590"


def to_mfa_page(ua: requests.Session, start: str = RP + "/login") -> str:
    """Follow the RP's redirect to Dex, post the password, stop at the MFA page."""
    r = ua.get(start, allow_redirects=False)
    print("1. RP /login ->", r.status_code, r.headers["Location"].split("?")[0])
    r = ua.get(r.headers["Location"])                  # Dex shows the login form
    action = urljoin(r.url, re.search(r'action="([^"]+)"', r.text)[1]
                     .replace("&amp;", "&"))
    print("2. Dex login form at", urlsplit(r.url).path)
    r = ua.post(action, data={"login": "[email protected]",
                              "password": "correct-horse-lab-7"})
    mode = re.search(r'const mode = "(\w+)"', r.text)
    print("3. password accepted, MFA page", urlsplit(r.url).path,
          "mode=" + (mode[1] if mode else "none"))
    return r.url


def passkey_step(ua: requests.Session, mfa_url: str, key: SoftKey,
                 origin: str = IDP_ORIGIN, honest: bool = True) -> requests.Response:
    query = urlsplit(mfa_url).query
    base = IDP_ORIGIN + "/dex/mfa/webauthn"
    page = ua.get(mfa_url).text
    kind = "register" if 'const mode = "register"' in page else "login"
    options = ua.post(f"{base}/{kind}/begin?{query}").json()
    if kind == "register":
        answer = key.create(options, origin)
    else:
        answer = key.get(options, origin, honest_browser=honest)
    r = ua.post(f"{base}/{kind}/finish?{query}", json=answer)
    print(f"4. passkey {kind} as {origin} ->", r.status_code,
          r.json().get("error", "accepted, continue at /dex/auth"))
    return r


def full_login() -> requests.Session:
    ua = requests.Session()
    r = passkey_step(ua, to_mfa_page(ua), SoftKey())
    r = ua.get(urljoin(IDP_ORIGIN, r.json()["redirect"]))  # Dex -> RP -> answer
    print("5. back at RP:", r.status_code, r.text)
    ua.last_callback = r.history[-1].headers["Location"]  # kept for attacks.py
    r = ua.get(RP + "/admin")
    print("6. RP /admin ->", r.status_code, r.text)
    return ua


if __name__ == "__main__":
    full_login()
    sys.exit(0)
Terminal
python browser.py
Expected output
1. RP /login -> 302 http://localhost:5590/dex/auth
2. Dex login form at /dex/auth/local/login
3. password accepted, MFA page /dex/mfa/webauthn mode=register
4. passkey register as http://localhost:5590 -> 200 accepted, continue at /dex/auth
5. back at RP: 200 signed in: {"email": "[email protected]", "acr": null, "amr": null}
6. RP /admin -> 403 step-up required: no acr/amr proof of phishing-resistant MFA

Line 4 is a real registration that Dex accepted, and line 5 a valid ID token for [email protected]. Line 6 is a surprise: the RP refuses /admin because the token does not say how ana authenticated. Step 7 explains why.

05. Step 4: Sign in with the passkey and read the token

Run the login again. Dex now holds ana's public key, so it asks for an assertion instead of a registration. Then print the claims that the RP validated.

Python · idp-lab/show_claims.py
"""Print the claims of the last ID token. Display only: rp.py did the validation."""
import jwt

claims = jwt.decode(open("last_id_token.txt").read(),
                    options={"verify_signature": False})  # never do this for access
for name in ("iss", "aud", "sub", "email", "email_verified"):
    print(f"{name:15}{claims[name]}")
names = sorted(claims)
print("all claims:   ", ", ".join(names[:7]))
print("              ", ", ".join(names[7:]))
print("acr / amr:    ", claims.get("acr"), "/", claims.get("amr"))
Terminal
python browser.py
python show_claims.py
Expected output
1. RP /login -> 302 http://localhost:5590/dex/auth
2. Dex login form at /dex/auth/local/login
3. password accepted, MFA page /dex/mfa/webauthn mode=login
4. passkey login as http://localhost:5590 -> 200 accepted, continue at /dex/auth
5. back at RP: 200 signed in: {"email": "[email protected]", "acr": null, "amr": null}
6. RP /admin -> 403 step-up required: no acr/amr proof of phishing-resistant MFA
iss            http://localhost:5590/dex
aud            notes-app
sub            CiQ2ZjFjMmE5ZS0wYjdkLTRjNTUtOWExZS0yYjNjNGQ1ZTZmNzASBWxvY2Fs
email          [email protected]
email_verified True
all claims:    at_hash, aud, auth_time, c_hash, email, email_verified, exp
               iat, iss, jti, name, nonce, sid, sub
acr / amr:     None / None

sub is the stable user ID to key accounts on; email addresses change. auth_time records when ana last authenticated. There is no acr (authentication context class) or amr (authentication methods, RFC 8176): Dex v2.46.0 does not issue them.

06. Step 5: Attack every check

attacks.py logs in once for real, to hold a genuine token and callback URL, then attacks each check. Every result must be REJECTED. The last test plays an adversary-in-the-middle kit: it relays ana's password to Dex and shows Dex's passkey challenge to ana on a look-alike origin.

Python · idp-lab/attacks.py
"""Negative tests against the lab RP and the lab IdP: each must be REJECTED."""
import base64
import json
import re
from urllib.parse import parse_qs, urljoin, urlsplit

import requests

import browser
from oidc_check import TokenRejected, validate_id_token
from softkey import SecurityError, SoftKey

DEX = browser.IDP_ORIGIN + "/dex"
PHISH = "http://dex-login.lab-phish.test:8099"  # the attacker's look-alike origin


def report(name: str, rejected: bool, reason: str) -> None:
    print("REJECTED" if rejected else "ACCEPTED <-- this is a bug", name)
    print("        ", reason)


def expect_reject(name: str, fn) -> None:
    try:
        fn()
        report(name, False, "no error raised")
    except (TokenRejected, SecurityError) as exc:
        report(name, True, str(exc))


def expect_http_reject(name: str, r: requests.Response) -> None:
    if "json" in r.headers.get("Content-Type", ""):
        body = r.json()
        reason = body.get("error_description") or body.get("error") or str(body)
    else:
        text = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", r.text)).strip()
        reason = text[text.find("Bad Request"):] if "Bad Request" in text else text
    report(name, r.status_code >= 400, f"{r.status_code} {reason}")


print("--- a genuine login, to get a real token and callback URL ---")
victim = browser.full_login()
token = open("last_id_token.txt").read()
nonce = json.loads(base64.urlsafe_b64decode(token.split(".")[1] + "=="))["nonce"]

print("--- ID token checks in the RP ---")
head, body, sig = token.split(".")
claims = json.loads(base64.urlsafe_b64decode(body + "=="))
claims["email"] = "[email protected]"
forged = base64.urlsafe_b64encode(json.dumps(claims).encode()).rstrip(b"=").decode()
expect_reject("tampered payload", lambda: validate_id_token(
    f"{head}.{forged}.{sig}", audience="notes-app", nonce=nonce))
expect_reject("token issued to another app", lambda: validate_id_token(
    token, audience="reports-app", nonce=nonce))
expect_reject("wrong issuer configured", lambda: validate_id_token(
    token, audience="notes-app", nonce=nonce, issuer="http://127.0.0.1:5590/dex"))
expect_reject("nonce from another login", lambda: validate_id_token(
    token, audience="notes-app", nonce="nonce-of-a-newer-login"))

print("--- callback checks in the RP ---")
expect_http_reject("forged callback (CSRF)", requests.get(
    browser.RP + "/callback?code=attacker-code&state=attacker-state"))
expect_http_reject("callback URL replayed", victim.get(victim.last_callback))

print("--- checks in the IdP ---")
expect_http_reject("unregistered redirect_uri", requests.get(DEX + "/auth", params={
    "response_type": "code", "client_id": "notes-app", "scope": "openid",
    "redirect_uri": "http://127.0.0.1:8099/steal", "state": "s",
    "code_challenge": "x" * 43, "code_challenge_method": "S256"}))

ua = requests.Session()                         # another real login ...
done = browser.passkey_step(ua, browser.to_mfa_page(ua), SoftKey())
next_url = urljoin(browser.IDP_ORIGIN, done.json()["redirect"])
while "/callback" not in next_url:              # follow Dex, but stop before the RP
    r = ua.get(next_url, allow_redirects=False)
    next_url = urljoin(browser.IDP_ORIGIN, r.headers["Location"])
code = parse_qs(urlsplit(next_url).query)["code"][0]  # ... whose code is stolen
expect_http_reject("stolen code, no PKCE verifier", requests.post(
    DEX + "/token", auth=("notes-app", "notes-app-lab-secret"), data={
        "grant_type": "authorization_code", "code": code,
        "redirect_uri": "http://127.0.0.1:8090/callback"}))

print("--- passkey relayed through a phishing page ---")
ua = requests.Session()                         # the kit relays the password ...
query = urlsplit(browser.to_mfa_page(ua)).query
options = ua.post(f"{DEX}/mfa/webauthn/login/begin?{query}").json()
key = SoftKey()                                 # ... and shows Dex's challenge
expect_reject("honest browser on phishing page", lambda: key.get(options, PHISH))
relayed = key.get(options, PHISH, honest_browser=False)
expect_http_reject("assertion made on phishing page", ua.post(
    f"{DEX}/mfa/webauthn/login/finish?{query}", json=relayed))
Terminal
python attacks.py
Expected output
--- a genuine login, to get a real token and callback URL ---
1. RP /login -> 302 http://localhost:5590/dex/auth
2. Dex login form at /dex/auth/local/login
3. password accepted, MFA page /dex/mfa/webauthn mode=login
4. passkey login as http://localhost:5590 -> 200 accepted, continue at /dex/auth
5. back at RP: 200 signed in: {"email": "[email protected]", "acr": null, "amr": null}
6. RP /admin -> 403 step-up required: no acr/amr proof of phishing-resistant MFA
--- ID token checks in the RP ---
REJECTED tampered payload
         InvalidSignatureError: Signature verification failed
REJECTED token issued to another app
         InvalidAudienceError: Audience doesn't match
REJECTED wrong issuer configured
         InvalidIssuerError: Invalid issuer
REJECTED nonce from another login
         nonce mismatch: token was not minted for this login
--- callback checks in the RP ---
REJECTED forged callback (CSRF)
         400 rejected: state does not match this browser (CSRF?)
REJECTED callback URL replayed
         400 rejected: state already used or unknown (replay?)
--- checks in the IdP ---
REJECTED unregistered redirect_uri
         400 Bad Request Unregistered redirect_uri.
1. RP /login -> 302 http://localhost:5590/dex/auth
2. Dex login form at /dex/auth/local/login
3. password accepted, MFA page /dex/mfa/webauthn mode=login
4. passkey login as http://localhost:5590 -> 200 accepted, continue at /dex/auth
REJECTED stolen code, no PKCE verifier
         400 Expecting parameter code_verifier in PKCE flow.
--- passkey relayed through a phishing page ---
1. RP /login -> 302 http://localhost:5590/dex/auth
2. Dex login form at /dex/auth/local/login
3. password accepted, MFA page /dex/mfa/webauthn mode=login
REJECTED honest browser on phishing page
         page http://dex-login.lab-phish.test:8099 may not use RP ID 'localhost'
REJECTED assertion made on phishing page
         401 Authentication failed.
Terminal · what Dex logged
docker logs "$DEX" 2>&1 \
  | grep -oE 'msg="(unregistered redirect_uri|webauthn login failed)"( err="[^"]*")?'
Expected output
msg="unregistered redirect_uri"
msg="webauthn login failed" err="Error validating origin"

The token checks run in the RP. The tampered payload breaks the signature. The token for another app fails on aud: Dex signed it, but for notes-app. The wrong issuer fails on an exact string comparison: 127.0.0.1 and localhost reach one server but are different issuer identifiers. The forged callback has no state cookie, and the replay fails because each state is removed when first used.

The last three checks are Dex's. It refuses an unregistered redirect_uri before showing a login page, refuses a code without the PKCE verifier even with the correct client secret, and rejects an assertion signed for the phishing origin.

07. Step 6: The three trust relationships

A federation is three trust relationships, each with its own evidence:

  • RP trusts IdP. It accepts a user statement only if signed by a key at the configured issuer's jwks_uri, with that exact iss, this RP in aud, a future exp and this login's nonce. The issuer URL is configuration, never taken from the token.
  • IdP trusts RP. Dex sends a code only to a redirect_uri registered for the client, compared as an exact string (RFC 9700 section 2.1), and redeems it only with the client secret and PKCE verifier. The secret belongs in an environment variable or vault and is rotated if it leaks.
  • User trusts IdP. ana authenticates to Dex only. The RP never sees her password, and her passkey is bound to the RP ID localhost.

The browser carries every message but nobody trusts it, which is why state, nonce and PKCE exist. SAML 2.0 has the same three relationships. The app trusts an XML assertion only if the IdP's key, from the certificate in its metadata, signed it, and it checks the audience (its entity ID), the recipient (its consumer URL), the validity window and the request ID. HTTPS from the browser proves nothing about who wrote the assertion, and nor does encryption to the app's public key, since anyone can encrypt to a public key. See the OWASP SAML Security Cheat Sheet.

08. Step 7: Requiring phishing-resistant MFA at the RP

Dex enforces phishing-resistant MFA here: defaultMFAChain: [lab-passkey] puts every client through the WebAuthn step, and step 5 showed Dex rejecting a phished assertion. The RP cannot see it. Without acr or amr, notes-app's belief rests on configuration, the client's MFA chain, verified by review and tests like this lab. So /admin stays closed: it requires an acr of phr or phrh (the phishing-resistant values of OpenID Connect EAP ACR Values 1.0) or an amr containing hwk.

Another limit: Dex v2.46.0 accepts a userVerification config field but does not pass it to its WebAuthn library. In our test, an assertion with only the user-present flag was accepted, so here the passkey is a possession factor next to the password.

With an IdP that issues acr, the RP can demand assurance per login. In Keycloak 26 you set the WebAuthn Passwordless Policy with User Verification Requirement set to required, add a Conditional - Level Of Authentication step that uses the WebAuthn Passwordless Authenticator, and map phr to that level in ACR to LoA Mapping. The RP requests the level, and the ID token carries the acr achieved. This sketch is illustrative and was not run here.

Python · illustrative change to rp.py for an IdP that issues acr
# In login(): ask for phishing-resistant authentication as an essential claim.
claims = {"id_token": {"acr": {"essential": True, "values": ["phr", "phrh"]}}}
query = urlencode({..., "acr_values": "phr", "claims": json.dumps(claims)})

# In callback(): after validate_id_token, refuse a weaker login outright,
# or send the user back with prompt=login to step up.
if claims.get("acr") not in STRONG_ACR:
    self.reply(403, "phishing-resistant MFA required")

09. Step 8: Clean up

Terminal
kill $RP_PID
docker rm -f "$DEX" > /dev/null && echo "lab IdP removed"
Expected output
lab IdP removed

10. Troubleshooting

11. Check your understanding

Practice check · 3 questions

Federation checks

Three questions about the lab you just ran.

Q1. A teammate sets `ISSUER` in `oidc_check.py` to `http://127.0.0.1:5590/dex`, because that is where Docker publishes Dex. What happens when they start `rp.py`?
Q2. In step 5 the replayed callback URL was rejected. Which check stopped it?
Q3. Notes-app must open `/admin` only after phishing-resistant MFA, and Dex's ID tokens carry no `acr` or `amr`. What is a sound basis for meeting this rule?
Practice only: not graded, not saved, not evidence.

12. Apply it

Extend the lab toward the skill project:

  • Copy rp.py as a reports-app RP on 127.0.0.1:8091 and confirm that each app rejects the other's ID token.
  • Give reports-app mfaChain: [], restart Dex, and watch it skip the passkey page. Note why such an exemption needs an owner and a review date.
  • Repeat the federation with Keycloak, using its WebAuthn Passwordless Policy and an acr mapping, and open /admin only for phr.

13. Review prompt

Without looking back, explain: what the discovery document and the JWKS give the RP; which five checks the RP makes on an ID token and what each one stops; what state, nonce and PKCE each protect; why Dex checks the redirect_uri before showing a login page; the three trust relationships in a federation and the evidence each relies on; what a SAML service provider must check in an assertion; and why notes-app cannot prove from Dex's token that a passkey was used.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check