Testing an OAuth integration
The paths that matter most in 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. code are the ones a demonstration never takes: a 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. for the wrong audience, a callback carrying someone else's state, two workers refreshing one connection in the same second. Tests exercise them before an attacker or a busy night does.
Tokens built to fail
None of those paths happens when a developer connects a test account and sees photos appear, so each needs a test that makes it happen on purpose.
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.'s validator is the easiest place to start, because it behaves like a function: a token goes in and a decision comes out. The tests generate their own signing key, configure the validator to trust it as the issuerThe party that creates and signs a token, assertion, or certificate, named in a token's iss claim. A recipient must check that the issuer is exactly the one it expected and trusts.'s key for the length of the test run, and sign tokens that differ from a valid one in exactly one way:
| Test token | What it proves |
|---|---|
| A valid token | The validator accepts what it should. Without this test, a validator that rejects everything passes all the others. |
exp well in the past | Expired tokens are refused, beyond the allowed leeway. |
aud naming another API | Tokens meant for somewhere else are refused. |
iss of the staging authorization server | Only the configured issuer is trusted, even with a valid signature. |
typ of JWT instead of at+jwt | Another kind of JWT is not accepted as an access token. |
alg of none and no signature | Unsigned tokens are refused. |
alg of HS256, using the public key as an HMAC secret | The algorithm comes from configuration, not from the token. |
Signed by a different key under the same kid | The signature is really checked. |
A kid the key set does not contain | An unknown key leads to one fetch of the key set and then a rejection. |
The photo API's validator
- A valid token
- Accepted
- exp well in the past
- Refused
- aud naming another API
- Refused
- iss of the staging server
- Refused
- alg of none
- Refused
Every test passes
Rejects everything
- A valid token
- Refused
- exp well in the past
- Refused
- aud naming another API
- Refused
- iss of the staging server
- Refused
- alg of none
- Refused
Only the valid-token test fails
Without this test, a validator that rejects everything passes all the others.
All values in these examples are fictional, and the test keys exist only inside the test run. A shortened sketch shows the shape. The validator receives a fixed clock, so the results do not depend on when the tests run:
const now = 1790845300; // 2026-10-01 09:01:40 UTC
const valid = {
iss: 'https://auth.photos.example', sub: 'user-2048',
aud: 'https://api.photos.example', client_id: 'photo-printer',
scope: 'photos.read', iat: 1790845200, exp: 1790845800, jti: 'demo-token-id-7',
};
test('accepts a valid token', async () => {
const token = await sign(valid, testKey);
expect((await validate(token, { now })).ok).toBe(true);
});
test('rejects an expired token', async () => {
const token = await sign({ ...valid, iat: 1790844000, exp: 1790844600 }, testKey); // 08:40 to 08:50
expect((await validate(token, { now })).ok).toBe(false);
});
test('rejects a token signed by another key with the same kid', async () => {
const token = await sign(valid, otherKey);
expect((await validate(token, { now })).ok).toBe(false);
});The last case avoids a common trap. Changing one character of a valid token's 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. looks like a simpler way to test a bad signature, but the final character of a Base64urlA way of encoding data as ordinary text characters so it can travel safely in headers, URLs, and JSON. Anyone can decode it, so it hides nothing; Base64url is a variant safe for URLs, used in JWTs. string can include unused bits, so some edits decode to exactly the same signature bytes and the "tampered" token is still valid. Signing with a different key produces a signature that is certainly wrong.
Testing the client's checks
The printer's callback handler has its own list. Each test starts a real attempt through the transaction store, then delivers a callback that is wrong in one way:
- A
statethat matches no pending attempt is refused. - A
statefrom an attempt started in a different 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. is refused. - The same callback delivered twice is processed once.
- An unexpected
iss, or none when the metadata says the server sends it, is refused before the code is used. - An
access_deniedresponse goes through the same checks and then shows the "not connected" message. - Every 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. request carries a fresh
S256challenge, and two attempts never share a verifier.
The tests run against a fake 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. that records every request it receives, so a refused callback can be shown to have sent nothing. That matters as much as the message on screen: a callback handler that displays an error after exchanging the code has already done the damage.
Above these sit integration tests against a real 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.. The printer cannot run a copy of the photo service, so it uses two kinds. In automated builds it starts a local authorization server, an open-source implementation run in a container, a packaged copy of a program that starts the same way on any machine, configured with test clients, and drives the full flow with a scripted browser, a real browser that test code controls, clicking Connect and approving as a test account would. Before each release it runs the same flow against the photo service itself, using the photo-printer-test client and dedicated test accounts. The local server catches the printer's own mistakes quickly. The real one catches the differences between how the printer believes the photo service behaves and how it actually does.
A team that runs an authorization server tests the other side: a redirect URI that differs by a trailing slash is refused without a redirect, a code is refused the second time, and a wrong verifier produces invalid_grant.
Testing under concurrency
The refresh coordinator from Implementing a client exists to prevent a race, and races do not appear in tests that do one thing at a time. A concurrency test starts two calls for the same connection at the same moment, against a fake authorization server that rotates refresh tokens:
test('two callers share one refresh', async () => {
await tokenStore.replace('conn-1', tokensAboutToExpire);
const [first, second] = await Promise.all([
currentAccessToken('conn-1'),
currentAccessToken('conn-1'),
]);
expect(fakeAuthServer.refreshRequests).toBe(1);
expect(first).toBe(second);
});Run against a coordinator without its lock, this test fails. The fake server sees two refreshes, the second presents a refresh tokenA longer-lived credential that a client sends to the authorization server, never to an API, to get new access tokens without asking the person again. the first has already spent, and a server with reuse detection would revokeCancelling a credential, token, certificate, or authenticator before it would expire, so that it is no longer accepted. Whether every copy stops working at once depends on how services check it. the whole family. That is precisely the failure the test exists to catch. When the coordinator runs on several servers, the test needs to exercise the shared lock, because a lock held in one process's memory protects only that process.
A second test makes the fake server accept a refresh and then drop the response. The printer should end up either with a working replacement or with the connection marked as needing attention, and never retrying in a loop. Operating and monitoring an integration looks at that retry decision.
Test clients, accounts, and suites
Tests need identities, and real ones are the wrong choice. The printer's tests use the photo-printer-test client, whose registration allows only the test site's redirect URIs, and photo accounts created for testing that contain nothing private. Their credentials live in the test secrets store. A test that reached for production by mistake would fail, because nothing in the test configuration works there.
For widely used profiles, published test suites exist. The OpenID Foundation's conformance suite tests OpenID Connect and FAPI implementations, as Interoperability and conformance testing describes, and some authorization server products publish their results. A passing suite shows that an implementation handles the cases the suite contains. It says nothing about the printer's sessions, its token store, or the lock on its refresh coordinator, which is why the printer's own tests stay in place.
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
- Write tests for your validator, your callback checks and your refresh lockBuild a validator suite from real fixture tokens, test that the client's callback refuses bad responses before sending anything, prove the refresh lock under concurrency, and see why a positive control matters.