Implementing a relying party
Over the OpenID ConnectAn identity layer on top of OAuth 2.0 that lets an application sign people in with an account at another service. It adds the ID token, standard claims, and discovery to the OAuth exchange. lessons, the collage app's sign-in buttons collected a long list of duties. This lesson follows the collage app's developers as they build them: what to take from a library, what the configuration holds, the order in which the callback handler meets each check, the attacks those checks stop, and the seams that let tests reach every failure.
Choosing a library
The collage app offers two buttons, Continue with your photo account and Continue with your mail account, and behind them sits everything the earlier lessons asked of a relying partyAn application that accepts and relies on a sign-in from another service, the name used in OpenID Connect and for passkeys. SAML calls the same role a service provider.. It creates a pending sign-in, checks the response, exchanges a code, validates an ID tokenIn OpenID Connect, a signed JWT from the provider, addressed to one client, saying which account authenticated, when, and in answer to which request. It reports a sign-in and is not used to call APIs. claim by claim, asks the UserInfo endpointAn OpenID Provider endpoint that returns claims about the signed-in person to a client presenting an access token. Its sub must match the ID token's before the client uses anything it returns. about Ava, finds her collage account and starts a sessionThe ongoing connection between later requests and an earlier sign-in, so you are not asked for your password on every click. It is often tracked with a cookie holding an unpredictable session identifier. of its own. Later it refreshes access without mistaking that for her presence, asks for a recent sign-in before she changes her delivery address for printed collages, and ends sessions when she or a provider signs out. All domains, identifiers, credentials and tokens in these examples are fictional.
Now the collage app's developers have to build it. Most of that work is deciding what to write themselves and what to rely on, then connecting the pieces so that no check can be quietly skipped.
Very little of the protocolAn agreed set of rules for the messages two systems exchange and what each message means. HTTP, OAuth 2.0, OpenID Connect and SAML are all protocols. should be the collage app's own code. Parsing a JWTA JSON Web Token: a compact token made of Base64url-encoded parts that carries claims and is usually signed. Anyone holding it can decode and read the claims, so the signature shows who issued it but hides nothing., choosing a key by kid, verifying an RS256 signatureA value made with a private key that lets anyone holding the matching public key check that a message came from the key's holder and has not been changed. It proves origin and integrity; it does not hide the message., caching a key setA JSON document, published at a fixed HTTPS address, that lists an issuer's current public keys so others can verify its signatures. It never contains private keys. and refetching it when a new key appears: each is easy to get almost right, and an almost-right signature check is worse than none, because it looks finished. A maintained OpenID Connect library, code that other people write and test for many applications, has already met the edge cases, and its maintainers fix the ones found later.
That library guards sign-in, so it deserves more scrutiny than most dependencies. Implementing a client, in the OAuthA framework that lets a person give an application limited access to their resources at another service, using tokens instead of sharing their password. OAuth is about access; OpenID Connect adds sign-in. lessons on implementation and operations, covers what to look for in an OAuth library. A relying party adds its own list:
- It is certified for the relying party profiles the collage app uses, meaning it passed the OpenID Foundation's published tests for them, such as the code flow with configuration from discovery. Conformance testing explains what that certificationA scheduled or triggered check in which a responsible person looks at access someone already has and decides whether they should keep it. It is also called certification, and it leaves a record of who decided what. does and does not tell you.
- It validates ID tokens itself, with every check from Validation and trust on by default, and reports which check failed rather than a bare "invalid tokenA piece of data issued by a trusted service that a client presents as a credential, for example to call an API or to report a sign-in. Some tokens carry readable claims; others are random strings that only the issuer can interpret.".
- It reads provider metadata through discovery, fetches keys from the provider's
jwks_uri, and refetches, within a limit, when a token names a key it has not seen. - It accepts only the signing algorithms the collage app configures, never
none, and never a key supplied inside the token. - It supports PKCE with
S256, theissauthorization response parameter, and several providers side by side. - It is actively maintained, publishes security fixes, and keeps tokens out of its own logs.
Some decisions no library can make for the collage app. Which collage account a subject belongs to, whether a new customer needs to finish registering, what a collage session records and how long it lasts, and what Ava may do once signed in are all the collage app's own. A library that offers to create or join accounts by matching email addresses is offering to make one of those decisions badly.
What the configuration holds
The library needs to be told what to trust. The collage app keeps one entry per provider, and every value in it is a decision explained in the Discovery and client configuration lessons, starting with Provider discovery:
providers:
photos:
issuer: https://auth.photos.example # compared exactly; discovery is read from here
client_id: photo-collage
client_auth: client_secret_basic
client_secret: loaded from the secret store at startup, never written here
redirect_uri: https://collage.example/signin/callback
scope: openid profile email
id_token_signing_algorithms: [RS256]
mail:
issuer: https://accounts.mail.example
client_id: c2d7a915-4e8b-4f03-a6d2-7b19e5f80c4d
redirect_uri: https://collage.example/signin/mail/callback
# its own credential, algorithms, and scopes, agreed with the mail serviceEndpoints and keys are missing on purpose. The library takes them from each provider's discovery document, after checking that the document's issuer equals the configured one, as Provider discovery described. A copied token endpoint or public key is a copy of something the provider may change, and the copy fails quietly the next time it does.
The client secret lives in a secret store, not in configuration files or source code. Each deployment also has its own registration, as Clients and registration recommended, so the collage app's test site signs in with a test client and a leaked test credential is useless against real customers. Rarer choices belong in configuration too, such as the max_age the collage app applies before an address change, where they can be reviewed in one place instead of rebuilt in each request.
The work in order
The callback handler is where most of those duties meet, so the collage app's developers write it to make one thing obvious: where an attempt stops. Every fail ends the attempt with the stage and the check that failed, and nothing after it runs.
params = parse_unique_callback_fields(request) # reject duplicate or ambiguous parameters
attempt = session.pending_signins.claim(params.state) # this browser's attempts only, once
if attempt is None or attempt.expired:
fail("callback", "no_pending_attempt")
provider = providers.get(attempt.issuer) # the provider this attempt went to
if request.callback_uri != attempt.redirect_uri: # each provider has its own return address
fail("callback", "wrong_return_address")
if provider.sends_iss and params.iss != provider.issuer: # the photo service sends iss; the mail service does not
fail("callback", "issuer_mismatch")
if params.error:
return show_outcome(params.error) # a denial is an answer, not a crash
if not params.code:
fail("callback", "missing_code")
tokens = require_usable_token_response(provider.exchange(params.code, attempt.verifier, attempt.redirect_uri))
claims = provider.validate_id_token(tokens.id_token, nonce=attempt.nonce,
max_age=attempt.max_age)
profile = provider.userinfo(tokens.access_token) # None if the call fails; the sign-in goes on
if profile is not None and profile.sub != claims.sub:
fail("userinfo", "subject_mismatch")
account = accounts.find(claims.iss, claims.sub) # never by email
if account is None:
return start_registration(claims, profile) # asks for whatever a missing profile left out
session.replace_with_new(account, issuer=claims.iss, subject=claims.sub,
auth_time=claims.auth_time, acr=claims.acr, sid=claims.sid,
id_token=tokens.id_token) # kept for a later logout hint
return redirect(attempt.return_page) # a local page checked when storedA few lines carry more weight than they show. claim finds the pending attempt among this browser's own and marks it used in the same step, so an expired attempt, a missing one, or a callback that arrives twice never reaches the token endpoint. A provider error is the end of this attempt, an answer to show Ava, with no identity and no code to redeem. If the token request times out, the collage app cannot know whether the photo service redeemed the code, so it starts a new attempt rather than sending the same code again.
state from this browser
claim: finds the pending attempt and marks it used
Exchange the code with the stored verifier
Validate the ID token with the nonce
Account found by issuer and subject
state already claimed
claim: no pending attempt
- stage
- callback
- check
- no_pending_attempt
Never reaches the token endpoint
require_usable_token_response exists because a 200 status is not a sign-in. The body must parse, and it must contain an ID token, which is validated before anything in the response is used, including the access token. The UserInfo call is allowed to fail: if the endpoint is down, the sign-in goes on from the validated ID token and registration asks for whatever is missing. A response for a different sub is another matter, and it stops the attempt rather than overwriting anything. Only after all of that does the collage app create a session, with a new identifier and its own deadlines, which the ID token's five-minute lifetime has nothing to do with.
The handler is one part of a longer list. Here is the order in which the collage app's code meets each responsibility:
| Moment | What the collage app does | Where the series covers it |
|---|---|---|
| Ava selects Continue | Creates a pending attempt with state, nonce, PKCE verifier, expected issuer, and return page, tied to this browser, and sends the request. | Following a complete sign-in; State and nonce |
| The callback arrives | Claims the attempt once, checks the return address, compares iss from a provider that sends it, and treats errors as outcomes. | Authentication errors; Supporting several providers |
| The token exchange | Authenticates, sends the code and verifier, and treats a lost response as unknown, not failed. | Receiving the ID token; Errors and denied access |
| The ID token | Checks the signature with an allowed algorithm and a key from jwks_uri, then iss, aud and azp, exp and iat, nonce, and auth_time and acr when requested. | Validation and trust |
| UserInfo | Requires the same sub as the ID token, and keeps the sign-in going if the call fails. | The UserInfo endpoint |
| The account | Looks up the issuer and subject pair, and links accounts only after both sides authenticate. | Connecting a sign-in to an account; Linking accounts |
| The session | Issues a new session identifier and records the issuer and subject, auth_time, acr, sid, and the ID token for a later logout hint. | Establishing an application session |
| Afterward | Refreshes without extending the session, asks for a recent sign-in before sensitive changes, and ends its own session first at logout. | Offline access and refresh behavior; Session age and reauthentication; RP-initiated logout |
A library can do every check in that table and still be undone by the code around it. A handler that logs a validation error and carries on with the claims, or a registration page that looks up accounts by the email in the profile, gives away what the library protected. That is why the handler treats each library result as a decision, not a warning.
The attacks the checks stop
Each check in the handler is there because of something someone could otherwise do. The Security Considerations section of OpenID Connect Core names the attacks, and current OAuth security guidance adds the ones it shares with OAuth. Read the other way round, the series is a list of answers:
| Attack | What it would look like at the collage app | The check that stops it |
|---|---|---|
| A forged or altered ID token | A token that names user-2048 but was never signed by the photo service | The signature, with an algorithm the collage app allows and a key from the photo service's jwks_uri, never none and never a key named inside the token (Signing keys and rotation) |
| Token substitution | A genuine ID token issued to another application, or about another person, presented in Ava's sign-in | aud must contain photo-collage with no audience the collage app does not trust, and iss must be the expected issuer (Issuer, audience, and authorized party) |
| Replay of an old token | Yesterday's ID token sent into today's sign-in | The nonce from this attempt, exp and iat, and a pending attempt that can be claimed once (Expiration and nonce checks) |
| A stolen or injected code | A code issued to someone else, delivered to the collage app's callback | The PKCE verifier, and the nonce checked inside the validated ID token, so a code from another attempt fails (State and nonce) |
| Login cross-site request forgery | An attacker's own sign-in response finished in Ava's browser, signing her in as the attacker | state tied to a pending attempt this browser started |
| Provider mix-up | A response from the mail service delivered where the collage app expects the photo service | A callback address and configuration entry per provider, and the iss response parameter where the provider sends it (Supporting several providers) |
| A masquerading provider | A look-alike discovery document that lists an attacker's endpoints and keys | Discovery fetched over HTTPS from the configured issuer, and its issuer compared exactly with the configured value (Provider discovery) |
| An access token used as proof of sign-in | Any working access token for the photo API treated as "this person just signed in here" | Only a validated ID token addressed to the collage app establishes a sign-in (From delegated access to sign-in) |
| Tokens disclosed in transit or at rest | Tokens in a URL fragment, a browser history, a referrer or a log | TLS everywhere, the code flow with a back-channel token request, and logs that record checks rather than tokens |
A few attacks the specification describes are the provider's to stop rather than the collage app's. Answering a password form with a 307 redirect would make the browser repeat the password to the relying party, so a provider answers with 303. A provider that serves many organizations must give each its own issuer, so that a relying party trusting one cannot be handed tokens from another. OpenID Provider responsibilities follows that side.
Reading the table this way also says what a missing check costs. Each row is a test the collage app's developers can write, with a token or response that should fail on exactly that check.
Leaving room to test
The collage app's tests cannot ask the photo service for a token signed with the wrong key or carrying yesterday's nonce. They need seams: places where a test can replace something the code normally takes from the outside world.
- The clock. If validation reads the time from a clock the test can set, a test can move it to 09:10 and confirm that the token that expired at 09:05 is refused, then move it back and confirm that the same token is accepted.
- The key source. A test key set lets tests sign tokens with a key the collage app trusts, with one it does not, and with a new
kidthat appears only after a refetch, asphotos-rs-2027-01will. - Random values. When state, nonce, and verifier come from one generator, a test can fix them and replay a recorded response against a known attempt.
- The provider. Because endpoints come from configuration and discovery, a test can point the collage app at a small stand-in provider that times out, answers
invalid_grant, or returns UserInfo for a differentsub.
Failures should come back as values a test can inspect: the stage, such as the callback or ID token validation, and the check, such as aud or nonce. A test can then assert that a token issued to another client failed on its audience, not merely that something failed somewhere. The same values go into the collage app's logs, where they make a failed sign-in explainable later.
A test also checks what did not happen. A token from the wrong issuer must not lead to a token exchange, a failed signature must leave no session and no change to any account, a callback that arrives twice must not create a second session, and a UserInfo response for another subject must copy nothing. These tests do not re-test the cryptography inside the library. They prove that the library's answer is what controls the collage app.
Check your understanding
Try these questions before moving on. If an answer isn't right, use the feedback and try again.
Try it in the Lab
- Build a callback handler that fails closedJudge btl-lab as the library, then connect it into a small relying-party handler that rejects stale callbacks before exchange, keeps unvalidated claims out of accounts and reports where each attempt stopped.