Accounts & Sign-In (TAD Case Study)
Ranked play, friends lists, saved progress and bans all need to know who a player is. Building your own login (password storage, resets, 2-step verification, social logins) is a large, risky project. Most games use an identity provider: a platform account (Steam, Epic, PlayStation, Xbox), a backend service's login, or an OpenID Connect (OIDC) server.
This lesson uses TAD, the identity server of the ExcelTAD ecosystem, as a worked example. Everything about TAD here comes from its integration contract (TAD Management's SSO_INTEGRATION_REQUIREMENTS.md, version 1.2); the requirement numbers (R2, R7, …) are that document's. The same patterns apply to any OIDC provider.
The pieces
player ─▶ game client (public OIDC client)
│ 1. browser sign-in: authorization code + PKCE
▼
TAD (issuer) ── tokens ──▶ game client
▲ │ 2. access token (Bearer)
│ JWKS (public keys) ▼
└──────────────── game backend (validates the JWT)
│ 3. short-lived connect ticket
▼
UDP game server- The game client signs the player in through TAD's hosted page and receives tokens. It never sees a password (R1).
- It calls the game backend (matchmaking, inventory) with the access token. The backend validates the token against TAD's public keys (R7).
- The backend hands out a connect ticket for one match. The real-time server checks the ticket instead of talking to TAD in the middle of a UDP handshake.
Step 1: sign-in with authorization code + PKCE
A game client is a public client: it ships to players, so it cannot keep a client secret. TAD requires the authorization code flow with PKCE (S256) (R2). The client:
- creates a random
code_verifier, astate(≥ 128 bits) and anonce; - opens the system browser at the authorization endpoint (read from discovery at
{issuer}/.well-known/openid-configuration) withresponse_type=code,client_id, the exactredirect_uri,scope(withopenid),state,nonce, andcode_challenge= BASE64URL(SHA-256(verifier)) withcode_challenge_method=S256; - receives the code on its redirect URI, checks
stateandiss(R3), and exchanges the code once, within 60 seconds, together with thecode_verifier.
The challenge is easy to compute. With the verifier from the PKCE specification (RFC 7636, Appendix B) we get the specification's answer:
function base64url(bytes: Uint8Array): string {
let s = '';
for (const b of bytes) s += String.fromCharCode(b);
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
async function s256(verifier: string): Promise<string> {
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
return base64url(new Uint8Array(digest));
}
// In a real client the verifier comes from crypto.getRandomValues (32 random bytes, base64url).
const verifier = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk';
console.log('code_verifier :', verifier);
console.log('code_challenge:', await s256(verifier));code_verifier : dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
code_challenge: E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
Only the challenge travels through the browser. If malware on the machine intercepts the code, it still can't redeem it without the verifier, which never left the game process.
Redirect URIs are matched exactly (§3). A browser game registers its page URL. A desktop game usually catches the redirect with a tiny HTTP listener on the loopback interface; with TAD that means registering one exact loopback URI with a fixed port (for example http://127.0.0.1:53682/callback) for each environment. Mobile games use AppAuth, which the contract suggests (§10).
Don't use an embedded web view for the sign-in page: TAD's sign-in uses a top-level navigation and forbids framing (R11), and a web view would let the game see the password field.
Step 2: tokens and what they are for
| Token | TAD format | Lifetime | Used by |
|---|---|---|---|
| ID token | JWT, typ: JWT |
15 min, checked once at sign-in | the client: who signed in (sub, sid, nonce) |
| Access token | JWT, typ: at+jwt |
15 min | sent as Authorization: Bearer to the game backend |
| Refresh token | opaque tadr_… |
30 days, rotates on every use | the client, to get new access tokens |
Rules that bite game developers:
- Key players by
sub, never by email (R5).subis stable forever; emails change. - Refresh tokens rotate (R9). Store the new one every time, never use one twice, and serialize refreshes. A reused refresh token is treated as theft and ends the whole session. Two game processes (the launcher and the game) refreshing in parallel is a classic way to sign every player out.
- Never send the ID token to the backend as if it were an access token (R7).
- Don't write tokens to logs or crash reports (R19).
Step 3: the backend validates access tokens
The game backend is a resource server. For every request it validates the access token (R7): RS256 signature with a key from the JWKS, header typ = at+jwt, iss = the issuer, aud = the game's client ID, exp in the future, token_use = user, then scope and roles for the operation. It caches the JWKS and refetches once when it meets an unknown kid (keys rotate).
In Node, the jose library does the cryptography:
import { createRemoteJWKSet, jwtVerify } from 'jose';
const ISSUER = 'https://<your TAD host>'; // from configuration, never hard-coded per build
const JWKS = createRemoteJWKSet(new URL(`${ISSUER}/.well-known/jwks.json`)); // caches keys
export async function authenticate(bearer) {
const { payload } = await jwtVerify(bearer, JWKS, {
issuer: ISSUER,
audience: process.env.GAME_CLIENT_ID,
typ: 'at+jwt',
algorithms: ['RS256'],
});
if (payload.token_use !== 'user') throw new Error('not a user token');
return { playerId: payload.sub, roles: payload.roles ?? [], sid: payload.sid };
}Here is a model of the same checks, with the signature check replaced by a key lookup so it runs anywhere and prints the same thing every time. It shows the order of the checks and the JWKS cache behaviour:
const ISSUER = 'https://tad.example';
const CLIENT_ID = 'tad_arena_game';
const NOW = 1_800_000_000; // fixed "current time" in seconds
let jwksFetches = 0;
const serverKeys = new Set(['key-2026-09', 'key-2026-10']); // what TAD publishes today
let cache = new Set(['key-2026-09']); // what we fetched last week
function fetchJwks() { jwksFetches++; cache = new Set(serverKeys); }
type Token = { header: { typ: string; kid: string }; claims: Record<string, unknown> };
function validate(t: Token): string {
if (!cache.has(t.header.kid)) fetchJwks(); // unknown kid: refetch once
if (!cache.has(t.header.kid)) return 'reject: unknown signing key';
// (a real server verifies the RS256 signature with that key here)
if (t.header.typ !== 'at+jwt') return `reject: typ ${t.header.typ} is not an access token`;
const c = t.claims;
if (c.iss !== ISSUER) return 'reject: wrong issuer';
if (c.aud !== CLIENT_ID) return 'reject: token was issued for another service';
if (typeof c.exp !== 'number' || c.exp <= NOW) return 'reject: expired';
if (c.token_use !== 'user') return 'reject: not a user token';
return `accept: player ${c.sub}, roles [${(c.roles as string[]).join(', ')}]`;
}
const good = { iss: ISSUER, aud: CLIENT_ID, exp: NOW + 600, token_use: 'user', sub: 'u_7f3a', roles: ['member'] };
const cases: [string, Token][] = [
['valid token', { header: { typ: 'at+jwt', kid: 'key-2026-09' }, claims: good }],
['new signing key', { header: { typ: 'at+jwt', kid: 'key-2026-10' }, claims: good }],
['ID token sent as Bearer', { header: { typ: 'JWT', kid: 'key-2026-10' }, claims: good }],
['token for another app', { header: { typ: 'at+jwt', kid: 'key-2026-10' }, claims: { ...good, aud: 'tad_other' } }],
['expired', { header: { typ: 'at+jwt', kid: 'key-2026-10' }, claims: { ...good, exp: NOW - 5 } }],
['forged key id', { header: { typ: 'at+jwt', kid: 'evil' }, claims: good }],
];
for (const [name, t] of cases) console.log(`${name.padEnd(24)} ${validate(t)}`);
console.log(`JWKS fetches: ${jwksFetches}`);valid token accept: player u_7f3a, roles [member]
new signing key accept: player u_7f3a, roles [member]
ID token sent as Bearer reject: typ JWT is not an access token
token for another app reject: token was issued for another service
expired reject: expired
forged key id reject: unknown signing key
JWKS fetches: 2
Note the last line: the forged kid costs a JWKS fetch. A real server rate-limits refetches (for example at most one per minute) so an attacker can't make it hammer the identity provider.
Self-validated access tokens stay valid for up to 15 minutes after a sign-out. For sensitive operations (real-money purchases, deleting a character, changing roles) TAD recommends asking it directly with POST /oauth/introspect (R8), which only confidential clients (backends with a secret) can call. A backend that keeps its own sessions also registers a back-channel logout endpoint (R15), so TAD can tell it when a player's session ends.
Step 4: a connect ticket for the game server
The real-time server speaks UDP and shouldn't fetch keys or parse JWTs during a handshake. A common pattern (used by many matchmaking systems) is a connect ticket: when the backend places the player in a match, it signs a tiny message with a secret shared only with its game servers.
const enc = new TextEncoder();
const key = await crypto.subtle.importKey('raw', enc.encode('server-fleet-secret-from-a-vault'),
{ name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']);
const hex = (b: ArrayBuffer) => [...new Uint8Array(b)].map((x) => x.toString(16).padStart(2, '0')).join('');
async function issueTicket(playerId: string, matchId: string, expires: number) {
const body = `${playerId}|${matchId}|${expires}`;
return `${body}|${hex(await crypto.subtle.sign('HMAC', key, enc.encode(body)))}`;
}
async function checkTicket(ticket: string, matchId: string, now: number) {
const parts = ticket.split('|');
const body = parts.slice(0, 3).join('|');
const ok = hex(await crypto.subtle.sign('HMAC', key, enc.encode(body))) === parts[3];
if (!ok) return 'reject: bad signature';
if (parts[1] !== matchId) return 'reject: ticket is for another match';
if (Number(parts[2]) < now) return 'reject: ticket expired';
return `accept ${parts[0]}`;
}
const ticket = await issueTicket('u_7f3a', 'match-118', 1_800_000_030); // valid for 30 s
console.log(ticket.slice(0, 48) + '…');
console.log(await checkTicket(ticket, 'match-118', 1_800_000_010));
console.log(await checkTicket(ticket, 'match-119', 1_800_000_010));
console.log(await checkTicket(ticket, 'match-118', 1_800_000_045));
console.log(await checkTicket(ticket.replace('u_7f3a', 'u_0001'), 'match-118', 1_800_000_010));u_7f3a|match-118|1800000030|ffd082bcb81488cf437d…
accept u_7f3a
reject: ticket is for another match
reject: ticket expired
reject: bad signature
(A real implementation compares signatures in constant time and uses a binary format; this one is readable on purpose.) The game server now knows the player's stable sub without ever seeing a TAD token.
Sign-out and session end
- Sign out from the game: delete local tokens, revoke the refresh token (
POST /oauth/revoke) and open/oauth/logoutwithid_token_hint(R14). This signs the player out of every TAD service in that browser. - A public client can't receive back-channel calls, so it treats
invalid_granton refresh, or a 401 that persists after one refresh, as "signed out" (R16). - During a match, don't kick a player the moment their access token expires; refresh in the background and only act when the session has really ended.
- If TAD answers
503(maintenance), keep players signed in and retry later (R17).
Test yourself
Why must a game client use PKCE instead of a client secret?
- PKCE is faster
- The client ships to players, so any embedded secret can be extracted; PKCE proves possession of a per-sign-in verifier instead
- Secrets are not allowed in OIDC
- PKCE encrypts the access token
The game backend receives a JWT whose header has typ: JWT. What should it do?
- Accept it if the signature is valid
- Reject it: that is an ID token, and only
at+jwtaccess tokens are accepted on APIs - Introspect it
- Refresh it
Your launcher and your game both hold the same refresh token and refresh at the same moment. What happens with TAD?
- Both get new tokens
- The second use of the old refresh token is treated as theft, and the whole session ends
- TAD ignores the second request
- Both requests fail with 429