A player banned during a match should lose access on the next protected request. For a gaming web app migrating off managed authentication, that requirement favors an opaque session over a locally validated JWT. Moving Google and GitHub sign-in is only part of the job. The game also needs control over the sessions those sign-ins create.
TL;DR: use opaque sessions for this browser app when the server must check current access on every request. Choose locally validated JWTs when avoiding that lookup matters more than immediate revocation, and define how long stale access is acceptable. Adding a revocation lookup to a JWT can be reasonable, but it gives up the purely stateless request path.
Keep identity stable.
This build log works through a migration rehearsal: preserve player IDs, create a small local session boundary, prove that logout invalidates a credential, and measure the lookup before distributing it. The code is an executable, single-process model. It deliberately leaves social callback verification at a trusted boundary; implementing either provider's callback protocol would be a separate integration.
Should a migrating web app choose an opaque session or JWT?
The first constraint is account continuity.
A player may have purchases, moderation history, and guild membership attached to an internal player ID. A successful social callback should resolve to that existing ID before issuing a new application session. Otherwise, a technically successful sign-in can create an empty account. That's a bad migration. Consider a rehearsal fixture with two external identities linked to player-42: both callbacks should resolve to that same internal player, and revoking that player's sessions should cover both entry points. If the second identity has no mapping, stop for authenticated linking instead of guessing from its email. This is the cutover acceptance criterion: successful authentication must preserve the game's account relationships, not merely produce a valid credential.
Use a verified external identity as the lookup key. For an OpenID Connect identity, the issuer and subject identify the user in that issuer's namespace. For another social protocol, use the provider's documented stable account identifier after its verification flow. Do not treat a matching email address as sufficient proof that two accounts belong to the same person. Treat linking as a sensitive account operation with appropriate authentication.
Save the TypeScript blocks, in order, in one file and execute it with a runtime that supports TypeScript execution. The identity values are fixtures, not real callback claims. The resolver fails closed on an unknown identity so the migration rehearsal exposes missing mappings before it can silently create replacement players. A production resolver needs persistent storage and an explicit, authenticated linking flow.
import assert from "node:assert/strict";
import { createHash, randomBytes } from "node:crypto";
import { performance } from "node:perf_hooks";
type VerifiedIdentity = { issuer: string; subject: string };
const identityKey = (identity: VerifiedIdentity) =>
JSON.stringify([identity.issuer, identity.subject]);
const identity = {
issuer: "https://identity.example",
subject: "fixture-player-42",
};
const players = new Map([[identityKey(identity), "player-42"]]);
function resolvePlayer(verified: VerifiedIdentity): string {
const playerId = players.get(identityKey(verified));
if (!playerId) throw new Error("Account linking required");
return playerId;
}
assert.equal(resolvePlayer(identity), "player-42");
assert.throws(() => resolvePlayer({ ...identity, subject: "unknown" }));
Passing these assertions establishes a narrow result: known identities retain their player ID, while an unmapped identity does not acquire one accidentally. It does not establish that a callback was authentic. Feed this function only identities produced by a verified sign-in flow, with the flow's state, redirect, and token checks applied as appropriate.
Now separate that identity handoff from session format. A provider access token is not automatically the credential the game's browser should send to its own backend. Keeping the application session behind a small interface makes the migration easier to inspect, and avoids dragging provider configuration through every request handler.
Build the smallest revocable session boundary
An opaque credential is a random secret whose meaning lives on the server. The browser holds the secret; the server resolves it to a session record. OWASP's Session Management Cheat Sheet describes server-side session meaning, unpredictable identifiers, expiration, and secure cookie handling. This implementation uses 32 random bytes and stores a SHA-256 digest as the lookup key. Those are implementation choices for this example, not measured security results.
The useful distinction is where the access decision happens. With this design, deleting the record makes the next lookup fail. A locally validated JWT instead carries claims that a verifier can accept without consulting this map; RFC 7519 defines claims including expiration, but a signature alone cannot tell the verifier that a player was banned a moment ago. Revocation therefore needs an additional mechanism, or access lasts until the verifier stops accepting the token.
type Session = { playerId: string; expiresAt: number };
class Sessions {
private readonly records = new Map<string, Session>();
private readonly byPlayer = new Map<string, Set<string>>();
private readonly now: () => number;
constructor(now: () => number = Date.now) {
this.now = now;
}
private key(token: string): string {
return createHash("sha256").update(token).digest("hex");
}
private remove(key: string, session: Session): void {
this.records.delete(key);
const keys = this.byPlayer.get(session.playerId);
keys?.delete(key);
if (keys?.size === 0) this.byPlayer.delete(session.playerId);
}
issue(playerId: string, ttlMs: number): string {
if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
throw new Error("Positive finite lifetime required");
}
const token = randomBytes(32).toString("base64url");
const key = this.key(token);
this.records.set(key, { playerId, expiresAt: this.now() + ttlMs });
const keys = this.byPlayer.get(playerId) ?? new Set<string>();
keys.add(key);
this.byPlayer.set(playerId, keys);
return token;
}
read(token: string): string | null {
const key = this.key(token);
const session = this.records.get(key);
if (!session) return null;
if (session.expiresAt <= this.now()) {
this.remove(key, session);
return null;
}
return session.playerId;
}
revoke(token: string): void {
const key = this.key(token);
const session = this.records.get(key);
if (session) this.remove(key, session);
}
revokePlayer(playerId: string): void {
for (const key of this.byPlayer.get(playerId) ?? []) {
this.records.delete(key);
}
this.byPlayer.delete(playerId);
}
}
Small interface. Real boundary.
The storage limitation is explicit: this map is not suitable for multiple application processes. Each process would see different records, and a restart would lose them. It also needs scheduled cleanup for expired records that are never read again.
The value is the contract.
Before production, move those operations into shared storage and define their consistency requirements. The trade-off is a dependency on that store for protected requests; local JWT validation avoids that dependency but cannot independently detect a newly revoked session.
At the HTTP boundary, issue the credential in a Secure, HttpOnly cookie over HTTPS. Choose SameSite behavior with the sign-in redirect flow in mind, and protect state-changing requests against CSRF. Cookie flags do not replace that analysis. Set an explicit lifetime, rotate the credential after authentication or privilege changes, and clear the browser cookie on logout while revoking the server record. Never put raw session tokens in logs.
A player ban also needs a durable account-status decision. Revoking existing sessions alone does not prevent the next social callback from issuing another one. Check that status before issuance and during authorization; make its interaction with concurrent sign-ins explicit.
Prove revocation, then benchmark the request path
Assertions come before latency numbers. Append this block to exercise single-session logout, player-wide revocation, and the exact expiration boundary without waiting for a clock. The 60,000-millisecond lifetime is a test fixture. It is not a recommended production policy.
let now = 0;
const sessions = new Sessions(() => now);
const playerId = resolvePlayer(identity);
const loggedOut = sessions.issue(playerId, 60_000);
assert.equal(sessions.read(loggedOut), playerId);
sessions.revoke(loggedOut);
assert.equal(sessions.read(loggedOut), null);
const deviceA = sessions.issue(playerId, 60_000);
const deviceB = sessions.issue(playerId, 60_000);
sessions.revokePlayer(playerId);
assert.equal(sessions.read(deviceA), null);
assert.equal(sessions.read(deviceB), null);
const expiring = sessions.issue(playerId, 60_000);
now = 60_000;
assert.equal(sessions.read(expiring), null);
assert.equal(sessions.read("unknown-token"), null);
const active = sessions.issue(playerId, 60_000);
const samples: number[] = [];
for (let i = 0; i < 1_000; i++) sessions.read(active);
for (let i = 0; i < 10_000; i++) {
const start = performance.now();
const result = sessions.read(active);
const elapsed = performance.now() - start;
assert.equal(result, playerId);
samples.push(elapsed);
}
samples.sort((a, b) => a - b);
console.log({
samples: samples.length,
p50Ms: samples[Math.ceil(samples.length * 0.50) - 1],
p95Ms: samples[Math.ceil(samples.length * 0.95) - 1],
});
No benchmark result is claimed here.
This harness measures a local digest and map lookup, with timer overhead, after 1,000 warm-up reads. It cannot predict a shared store's network latency. The next useful measurement is the same contract through the deployed storage adapter, including concurrent reads, revocations, timeouts, and the connection pool used by real requests. Record p50 and p95 in milliseconds; do not turn an in-memory number into a deployment promise.
Keep time-to-first-successful-sign-in separate from steady-state request latency. For a developer integrating a CLI or SDK around the game backend, an authentication change that adds configuration in five packages can cost more engineering attention than the small interface above suggests. Count the required settings and manual steps in the rehearsal.
Measure them.
A fair opaque-session versus JWT comparison also fixes the revocation requirement. Compare opaque reads against local JWT verification only if the accepted stale-access window differs explicitly. If both paths must consult current account status on every request, include that lookup in both measurements. Otherwise the faster number is answering a different question.
What changes at scale?
Shared storage becomes part of request availability. On a lookup timeout, reject or defer protected access according to an explicit failure policy; silently accepting an unverified session defeats the boundary. Record lookup latency, timeout counts, rejected sessions, and revocation propagation delay without recording credentials. A positive cache introduces a stale-access window, which must fit the moderation policy.
The single-process tests also leave out concurrent issuance during a ban and requests already authorized before revocation. Test those separately.
WebSocket connections need a policy too: an HTTP cookie check at connection establishment does not reauthorize every later game action. Decide whether sensitive messages trigger fresh checks or whether revocation disconnects the connection, and measure the resulting delay.
For cutover, inventory the old session contract and establish which identity mappings can actually be migrated. Do not assume a provider export contains reusable passwords, external identity links, or live sessions. Rehearse with representative fixture accounts, then stage the transition with explicit acceptance rules for old and new credentials. A rollback that starts accepting revoked old sessions would undo the access decision the migration was meant to preserve.
The operational bill includes storage, network calls, on-call ownership, and integration work. None of those disappears because a token has three encoded segments. JWTs can reduce dependence on a central session read when services can accept bounded stale claims; opaque sessions make a current server-side decision straightforward when the application already needs that authority.
For this browser game, require stable player IDs and demonstrable revocation before cutting over social sign-in. Keep opaque sessions if those checks belong on every protected request. Choose JWTs only with an explicit expiration and revocation design that meets the same game's access policy. Benchmark that design, including its failure path, before treating statelessness as a win.
References
The authentication guidance supports the identity and account-change boundaries. The session guidance supports identifier handling, cookies, expiration, and invalidation. The token and identity specifications define the claims and identifiers discussed above. Code constants and fixture accounts are illustrative design choices.
Sources
- OWASP Authentication Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html
- OWASP Session Management Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html
- RFC 7519, JSON Web Token: https://www.rfc-editor.org/rfc/rfc7519.html
- OpenID Connect Core, subject identifiers: https://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes
Top comments (0)