Implementing a client
Every client-side check from the earlier lessons has to live somewhere in real code, and where it lives decides whether it runs every time. The printer's rebuilt client wraps a maintained library, reads its endpoints from metadata, gives each job one home, and keeps its environments and secrets apart.
Starting from a library
The printing company is rebuilding its photo connection. The first version grew one function at a time: a handler for the Connect button, another for the callback, a December calendar job with its own copy of the refresh logic, and a helper for calling the photo APIAn application programming interface: a defined way for software to interact with a service. A web API offers endpoints where other programs send HTTP requests.. Each piece worked when it was written. Together they kept tokens in three places, refreshed them in two different ways, and read the photo service's token endpointThe authorization server address where clients exchange an authorization code, refresh token, or other grant for tokens, in a direct request rather than through a browser redirect. from a configuration file that nobody updated when the address changed.
Every client-side check from Correlating requests and responses to OAuth security best practices was missing from at least one of those pieces. The rebuild starts by deciding where each check lives, so that it also runs in the code someone adds next year.
Much of a client's 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. work is precisely specified and easy to get slightly wrong. Generating a PKCEProof Key for Code Exchange, pronounced pixie: the client creates a secret for each authorization attempt, sends only a hash of it at the start, and proves it holds the secret when redeeming the code, so a stolen authorization code is useless to anyone else. verifier and challenge, encoding an authorizationDeciding whether a requested action is permitted, such as whether a signed-in account may delete a particular photo. Authentication says which account is asking; authorization decides what it can do. URLA web address, such as https://photos.example/api/albums/42?limit=10. It names how to connect (https), the domain, the path to a particular page or resource, and any extra parameters after the question mark., comparing the iss response parameter, form-encoding a client secretA shared secret that a confidential client uses to prove itself to the authorization server, much like a password for an application. It belongs on a backend, never in code sent to browsers or phones. before HTTPThe Hypertext Transfer Protocol, the rules browsers, apps, and servers use to send requests and responses on the web. Basic, signing a client assertion, and parsing an error response each have a correct answer, and each has caught out hand-written code. A well-maintained 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. library has already met these problems, and its maintainers change it when security guidance changes.
Choosing one deserves some care. Look for active maintenance and a visible history of security fixes. Check that it supports what this integration needs: PKCE with S256, the iss response parameter, authorization serverIn OAuth, the service that handles a person's sign-in and approval and decides which tokens to issue to a client. It may belong to the same company as the API, but its job is separate. metadata, and the client authenticationChecking evidence that someone, or some application, controls an account, such as a password or a passkey. It establishes which account is being used, not what that account may do. method in the printer's registration. Prefer a library whose defaults are already safe, so that PKCE is on unless someone deliberately turns it off and the implicit grant is not offered at all. For 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., and for FAPI, a stricter profile of OAuth for high-value APIs such as banking, the OpenID Foundation certifies implementations that pass its conformance tests, and Interoperability and conformance testing, in Advanced OAuth, describes what such a result does and does not prove.
A library implements the protocol. It does not know what a printer account is, which session started an attempt, or what "connected" means to the printer's customers. The printing company therefore wraps the library in a small module of its own, and the rest of the application talks only to that module. Updating the library then means changing one module, and the team treats those updates like any other security fix.
Configuration from metadata
All domains, identifiers, and credentials in these examples are fictional. The printer's module starts from a handful of values:
issuer: https://auth.photos.example
client_id: photo-printer
redirect_uri: https://printer.example/oauth/callback
scope: photos.read
api_base: https://api.photos.exampleEndpoint addresses are missing on purpose. An authorization server can publish a small JSON document, its metadata, at a well-known address under its issuer, listing its endpoints and the features it supports. The module reads authorization_endpoint, token_endpoint, and revocation_endpoint from the photo service's metadata document at https://auth.photos.example/.well-known/oauth-authorization-server, after checking its issuer against the configured value. It handles that document the way Authorization server metadata, in Advanced OAuth, describes: it refreshes it on a schedule, keeps the last validated copy when a fetch fails, and raises an alert, rather than quietly changing its behavior, if a capability it relies on such as S256 disappears. If an endpoint answers 404 between scheduled fetches, the module reads the metadata again, once, and retries at the address it now lists. When the photo service moves its token endpoint, nobody at the printing company has to notice.
What stays in the module's own configuration is everything the printer decides for itself: which issuer it trusts, which client it is, where its callback lives, what access it asks for, and which API may receive its tokens. That division is worth keeping strict. A value the client should decide, such as its scope, never comes from a document the server publishes, and a value the server publishes, such as its token endpoint, is never copied into a file where it can go stale.
The parts of a client
Inside the module, the printer separates five jobs:
| Part | Its job |
|---|---|
| Transaction store | Creates the pending transaction when Ava selects Connect, and lets the callback claim it once, from the same session. |
| Callback handler | Checks the response against its transaction and expected issuer, exchanges the code, and saves the result. |
| Token store | Keeps each connection's tokens on the backend, encrypted, keyed by printer account and issuer. |
| Refresh coordinator | The only code that refreshes. It allows one refresh per connection at a time and saves a replacement refresh token before anything uses the new access token. |
| API caller | The only code that attaches an access token to a request, and only to the configured photo API. |
One function at a time
- Tokens kept
- In three places
- Refreshed
- In two different ways
- Token sent to
- Wherever a caller points
- Token endpoint from
- A file nobody updated
The endpoint moves: refreshes fail
One home for each job
- Tokens kept
- Token store
- Refreshed
- Refresh coordinator only
- Token sent to
- The configured photo API
- Token endpoint from
- Validated metadata
The endpoint moves: the module reads metadata again
A token goes only to the API it was issued for.
A shortened sketch shows how the last two fit together. It is written in TypeScript, the language of the printer's backend, and you can follow it without knowing the language: read await as "wait here for the database or the network to answer", and the comments say what each line is for. The oauth object stands for the wrapped library. withConnectionLock lets only one piece of code at a time work on a given connection; with one server that can be a lock on the connection's database row, and with several servers it must be a lock they all share, usually kept in the database or a cache:
async function currentAccessToken(connectionId: string): Promise<string> {
return withConnectionLock(connectionId, async () => {
const stored = await tokenStore.load(connectionId);
if (!stored) throw new NeedsReconnection(connectionId);
if (stored.accessTokenExpiresAt > Date.now() + 60_000) {
return stored.accessToken; // good for at least a minute
}
const result = await oauth.refresh(stored.refreshToken);
await tokenStore.replace(connectionId, result); // save first, then use
return result.accessToken;
});
}
async function callPhotoApi(connectionId: string, path: string): Promise<Response> {
const url = new URL(path, config.apiBase);
if (url.origin !== new URL(config.apiBase).origin) {
throw new Error('Refusing to send a photo API token to another host');
}
const token = await currentAccessToken(connectionId);
return fetch(url, { headers: { Authorization: `Bearer ${token}` } });
}The origin check writes a rule from Using access tokens into the one function that attaches tokens: a token goes only to the API it was issued for. It is needed because new URL treats a full address as replacing the base, so a path such as https://elsewhere.example/ would otherwise carry the token to another host. The photo picker and the December calendar job both call callPhotoApi, so both get the same refresh behavior and the same rule about where tokens may go. If two workers ask for the same connection at once, the second waits for the lock and then finds the fresh token the first one saved. When a refresh fails with invalid_grant, the coordinator marks the connection as needing reconnection, instead of letting each caller decide what that error means. A 401 from the API leads to one refresh and one retry, as Using access tokens described, and that logic belongs in the API caller for the same reason.
The callback handler follows the order the authorization code lessons taught in Correlating requests and responses and Errors and denied access: claim the transaction, compare the issuer, handle an error response, and only then exchange the code, sending it to the token endpoint taken from validated metadata. Keeping those steps in one handler makes their order visible and easy to test.
Environments and secrets
The printer's test website at https://test.printer.example runs the same code with a different configuration and its own registration at the photo service:
| Setting | Production | Test |
|---|---|---|
| Client ID | photo-printer | photo-printer-test |
| Redirect URI | https://printer.example/oauth/callback | https://test.printer.example/oauth/callback |
| Client credential | From the production secrets store | From the test secrets store |
| Photo accounts | Customers' accounts | Accounts created for testing |
The issuer is the same in both, because the test site connects to the photo service's real authorization server with test accounts. Everything that identifies the printer differs. If the test site accidentally loaded the production client ID, its first authorization request would fail at the photo service, because the test site's redirect URI is not registered for photo-printer. Separate registrations turn that configuration mistake into an error instead of a leak.
The client credential is the one value here that must stay private. The module reads it at run time from a secrets store, not from the repository or a file built into the packaged copy of the program that gets deployed. It never appears in logs, in error messages, or in process arguments, which other users of a machine can often read. Each environment has its own credential, so a developer with access to test credentials holds nothing that works in production. When the credential needs replacing, the overlap from Rotating client credentials applies, and a registration that uses private_key_jwt removes the shared secret altogether.
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 client module configured from metadata, with one place for each jobRun the printer's client module with a transaction store, callback handler, token store, refresh coordinator and API caller, then prove it survives an endpoint move and refuses misuse.