Beta

Create a tenant

A new tenant starts with its own users, OAuth settings, audit history and logs. You are its first Tenant Admin.

Implementing a relying party

Over the OpenID Connect 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 party. It creates a pending sign-in, checks the response, exchanges a code, validates an ID token claim by claim, asks the UserInfo endpoint about Ava, finds her collage account and starts a session 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 protocol should be the collage app's own code. Parsing a JWT, choosing a key by kid, verifying an RS256 signature, caching a key set 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 OAuth 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 certification 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 token".
  • 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, the iss authorization 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 service

Endpoints 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 stored

A 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

The first callback claims its attempt and goes on to the token endpoint. The same callback again finds nothing to claim and stops at the callback.

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:

MomentWhat the collage app doesWhere the series covers it
Ava selects ContinueCreates 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 arrivesClaims 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 exchangeAuthenticates, sends the code and verifier, and treats a lost response as unknown, not failed.Receiving the ID token; Errors and denied access
The ID tokenChecks 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
UserInfoRequires the same sub as the ID token, and keeps the sign-in going if the call fails.The UserInfo endpoint
The accountLooks up the issuer and subject pair, and links accounts only after both sides authenticate.Connecting a sign-in to an account; Linking accounts
The sessionIssues 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
AfterwardRefreshes 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:

AttackWhat it would look like at the collage appThe check that stops it
A forged or altered ID tokenA token that names user-2048 but was never signed by the photo serviceThe 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 substitutionA genuine ID token issued to another application, or about another person, presented in Ava's sign-inaud 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 tokenYesterday's ID token sent into today's sign-inThe nonce from this attempt, exp and iat, and a pending attempt that can be claimed once (Expiration and nonce checks)
A stolen or injected codeA code issued to someone else, delivered to the collage app's callbackThe 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 forgeryAn attacker's own sign-in response finished in Ava's browser, signing her in as the attackerstate tied to a pending attempt this browser started
Provider mix-upA response from the mail service delivered where the collage app expects the photo serviceA callback address and configuration entry per provider, and the iss response parameter where the provider sends it (Supporting several providers)
A masquerading providerA look-alike discovery document that lists an attacker's endpoints and keysDiscovery 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-inAny 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 restTokens in a URL fragment, a browser history, a referrer or a logTLS 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 kid that appears only after a refetch, as photos-rs-2027-01 will.
  • 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 different sub.

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.

The collage app's library validates ID tokens. A developer wraps the call in a handler that logs any validation error and then carries on with the token's claims. What is wrong? 1 of 3

Choose one answer.

Why does the collage app take its token endpoint and signing keys from the photo service's discovery document instead of copying them into its configuration? 2 of 3

Choose one answer.

Ava's browser delivers the same sign-in callback to the collage app twice. The first one has already signed her in. What should the handler do with the second? 3 of 3

Choose one answer.

Try it in the Lab

We value your privacy

We use cookies and similar technologies to enhance your browsing experience, and analytics to understand our traffic. By clicking "Allow all", you consent to optional analytics. Cookie Policy

Learn identity