jemgames / game-auth
Local JWT verification, guards and role middleware for JEM Games backends.
Requires
- php: ^8.3
- illuminate/auth: ^12.0|^13.0
- illuminate/cache: ^12.0|^13.0
- illuminate/console: ^12.0|^13.0
- illuminate/contracts: ^12.0|^13.0
- illuminate/encryption: ^12.0|^13.0
- illuminate/http: ^12.0|^13.0
- illuminate/routing: ^12.0|^13.0
- illuminate/session: ^12.0|^13.0
- illuminate/support: ^12.0|^13.0
- lcobucci/clock: ^3.0
- lcobucci/jwt: ^5.0
Requires (Dev)
- orchestra/testbench: ^10.0|^11.0
- pestphp/pest: ^4.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is not auto-updated.
Last update: 2026-12-01 20:25:39 UTC
README
Drop-in authentication for JEM Games backends. It verifies access tokens issued by the studio auth service (auth.jemgames.com) locally: no connection to the auth database, and no HTTP call while handling a request.
The auth service itself (studio-auth), its specification, an illustrated guide with screenshots and an example game live in the JEM Games SSO repository (hdctambien/jemgames-sso). This repository contains only the package that games install.
Supports Laravel 12 and 13 on PHP 8.3+.
It provides:
- the web login module (backend-for-frontend) for browser games:
/auth/login,/auth/callback,/auth/logoutand thejwt-sessionguard. Tokens stay in the game's server-side session; the browser only holds the game's own session cookie; - the
jwt-bearerguard for native clients: mobile and desktop apps, and consoles and TVs that sign in with a code (studio-auth's device flow, RFC 8628). Their tokens are identical, so nothing else is needed; - the
game-rolemiddleware.
The only outbound HTTP calls are the web module's code exchange at sign-in, a refresh shortly before the access token expires (about once per 15 minutes per player), and the revoke call at logout.
The production service
The studio auth service runs at https://auth.jemgames.com. That is also this package's default
GAME_AUTH_ISSUER, so a game in production only needs its own settings:
- A studio admin registers the game and its clients on the auth service (
game:register,game:client). That gives you the client ID and, for web clients, the secret once. - Signing keys come from
https://auth.jemgames.com/.well-known/jwks.json. Rungame-auth:refresh-keyson every deploy of your game and hourly (below), so that a key rotation on the auth service reaches your game before the old key is retired.
Install
Releases are git tags (v1.0.0, v1.1.0, …; semantic versioning). Until the package is on
Packagist, add this repository to the game's composer.json:
"repositories": [ { "type": "vcs", "url": "https://github.com/hdctambien/jemgames-auth" } ]
composer require jemgames/game-auth:^1.0
php artisan vendor:publish --tag=game-auth-config # optional
To work on the package and a game at the same time, point the game at a local checkout instead:
"repositories": [ { "type": "path", "url": "../JEMGamesSSOClient", "options": { "symlink": true } } ]
On filesystems without symlinks (such as VirtualBox shared folders) use "symlink": false, and run
composer update jemgames/game-auth in the game after each change, because the game then holds a copy.
Configure
.env:
GAME_AUTH_SLUG=dulce-bellum # this game's slug in studio-auth (required) GAME_AUTH_ISSUER=https://auth.jemgames.com GAME_AUTH_KEY_SOURCE=jwks # or "static" to list keys in config/game-auth.php GAME_AUTH_JWKS_URL= # default: {issuer}/.well-known/jwks.json GAME_AUTH_CACHE_STORE= # cache store for keys; default store if empty GAME_AUTH_LEEWAY=10 # clock-skew tolerance in seconds
If GAME_AUTH_SLUG isn't set, the package refuses to verify any token.
config/auth.php:
'guards' => [ // ... 'jwt-session' => ['driver' => 'jwt-session'], // web (BFF) players 'jwt-bearer' => ['driver' => 'jwt-bearer'], // native apps ],
Guard names match the driver names, so auth:jwt-session,jwt-bearer works as written below.
Signing keys
With key_source=jwks, keys are fetched by a command, never during a request:
php artisan game-auth:refresh-keys
Run it on every deploy and schedule it hourly (routes/console.php):
use Illuminate\Support\Facades\Schedule; Schedule::command('game-auth:refresh-keys')->hourly();
If a refresh fails (auth service down, bad response, or no usable keys), the previously cached keys are kept and the command exits with status 1. Tokens whose kid isn't in the cache are rejected.
Use a shared, persistent cache store (Redis, database) in production, so every app server sees the same keys. Ideally give the keys a store of their own (GAME_AUTH_CACHE_STORE).
Clearing the cache removes the keys. php artisan cache:clear or optimize:clear against that store means every token is rejected until keys are fetched again. Run game-auth:refresh-keys after any cache clear in your deploy script. When the key cache is empty, the package logs a warning that names this command.
Only RSA keys of at least 2048 bits are accepted. A JWKS that contains no such key is treated as a failed refresh.
Testing your game
Authenticate as a player in your own feature tests with actingAs:
use JemGames\GameAuth\AuthUser; $player = AuthUser::fromClaims(['sub' => '01JD8Z6Q4X3B7K9M2N5P0R1S2T', 'username' => 'PlayerOne', 'roles' => ['playtester']]); $this->actingAs($player, 'jwt-bearer')->getJson('/profile')->assertOk();
Web games (BFF)
Register a web client in studio-auth (php artisan game:client <slug> --kind=web --redirect=https://<game>/auth/callback) and add:
GAME_AUTH_CLIENT_ID=<web client id> GAME_AUTH_CLIENT_SECRET=<web client secret> GAME_AUTH_REDIRECT_URI=https://dulcebellum.example/auth/callback GAME_AUTH_POST_LOGOUT_REDIRECT_URI= # optional; default: origin of the redirect URI + web.home GAME_AUTH_VERIFY_TLS=true # false only for self-signed local *.test certificates GAME_AUTH_WEB=true # false disables the routes (API-only backends)
Other settings live under web in config/game-auth.php: route_prefix (auth), home (/, where players land after sign-in), refresh_before (60 seconds) and cache_store (refresh locks; it must support atomic locks, e.g. redis, database, file).
| Route | Name | What it does |
|---|---|---|
GET /auth/login?return=/decks |
game-auth.login |
Starts sign-in (state + PKCE S256) and redirects to the auth service. return must be a relative path; anything else is ignored. |
GET /auth/callback |
game-auth.callback |
Checks state, exchanges the code, verifies the token, regenerates the session id, stores the tokens and returns to return (or home). |
POST /auth/logout |
game-auth.logout |
Revokes this game's refresh token and clears the session. With everywhere=1 it then sends the player to the auth service's "log out everywhere" page. |
<a href="{{ route('game-auth.login', ['return' => request()->getRequestUri()]) }}">Sign in</a> <form method="POST" action="{{ route('game-auth.logout') }}"> @csrf <button>Log out</button> <button name="everywhere" value="1">Log out everywhere</button> </form>
Behaviour to know about:
- Several sign-ins may be pending at once (e.g. two tabs). Each
stateworks once and expires after 10 minutes. An unknown, replayed or expired state gets a 400. - If the auth service returns an error (e.g. the player cancelled), the player is sent to
homewith the code flashed assession('game_auth.error'). - If the code exchange fails or the token doesn't verify, the callback answers 502 and logs
game-auth: sign-in failed. - Refresh: within
refresh_beforeseconds of expiry the guard refreshes using the stored refresh token. A cache lock means one request refreshes; concurrent requests adopt its result. If the auth service rejects the refresh (invalid_grant), the tokens are cleared and the player is signed out. If it is unreachable, the player stays signed in until the access token expires. - Unauthenticated browser requests on
jwt-sessionroutes are redirected to/auth/login?return=…; JSON requests get401.
First sign-in: listen for JemGames\GameAuth\Events\PlayerSignedIn to create or update the game's player row, keyed by $event->user->id (the stable ULID), never by username:
Event::listen(PlayerSignedIn::class, fn (PlayerSignedIn $e) => Player::updateOrCreate( ['auth_id' => $e->user->id], ['username' => $e->user->username], ));
When studio-auth ends a session
The game never calls studio-auth to check a player, so ends take effect at the next refresh:
- a suspended or banned account, a per-game ban on this game (
user:game-status), logout everywhere, a password change, or a revoked client or deactivated game all make the refresh fail withinvalid_grant. The web module then clears the tokens and the player is signed out of this game; - a bearer token that was already issued stays valid until it expires (at most 15 minutes). Native apps and consoles should treat a failed refresh as "sign in again".
How the player signed in (password, 2FA, or Discord/Google/Steam) doesn't matter to the game: the token is the same.
Protect routes
Pick the guard by who calls the route:
// routes/web.php: browser players only (the `web` group gives session + CSRF) Route::middleware('auth:jwt-session')->group(function () { Route::get('/play', PlayController::class); }); // routes/api.php: native apps only Route::middleware('auth:jwt-bearer')->group(function () { Route::get('/profile', ProfileController::class); }); // routes/api.php: shared by browser and native players Route::middleware(['game-auth.stateful', 'auth:jwt-session,jwt-bearer'])->group(function () { Route::get('/decks', ListDecks::class); Route::post('/tournaments', CreateTournament::class) ->middleware('game-role:tournament_organizer,studio_admin'); });
Shared routes must use game-auth.stateful, not the web group. game-auth.stateful runs the app's web middleware (cookies, session, CSRF) only for requests without an Authorization: Bearer header. Native requests skip it, so their POSTs aren't rejected with 419, and they don't create session rows. Browsers must still send the CSRF token (_token field, or X-XSRF-TOKEN from the XSRF-TOKEN cookie).
Unauthenticated responses:
jwt-bearerroutes:401 {"message":"Unauthenticated."}withWWW-Authenticate: Bearer(no token) orBearer error="invalid_token"(rejected token).jwt-sessionroutes: browsers are redirected to/auth/login?return=…; JSON requests get401withoutWWW-Authenticate.- Shared routes: a request with a bearer token, or a JSON request, gets the bearer
401; any other request is treated as a browser and redirected.
game-role:a,b → 403 {"message":"Forbidden."} unless the user holds any of the listed roles. With no roles listed it always denies.
The authenticated user
$request->user() is an immutable JemGames\GameAuth\AuthUser, not an Eloquent model:
| Member | Value |
|---|---|
id |
Player ID (ULID, the token's sub). Key your game data on this. |
username |
Current username. It can change, so don't key data on it. |
emailVerified |
Whether the player has verified their email. |
roles |
Role slugs for this game, including global roles. |
clientId |
OAuth client the token was issued to. |
claims |
All verified token claims. |
hasRole('x'), hasAnyRole([...]) |
Role checks. |
hasPermission('decks.create') |
Checks config('game-auth.role_permissions'). |
Map roles to local abilities in config/game-auth.php:
'role_permissions' => [ 'playtester' => ['matchmaking.join', 'decks.create'], ],
What is verified
Every token must:
- use
RS256 - carry a known
kid - have a valid signature
- be within
iat/nbf/exp, give or take the leeway - have
issequal toGAME_AUTH_ISSUER - have
audcontainingGAME_AUTH_SLUG - have a non-empty
sub - have a
rolesclaim, if present, that is a list of strings
Testing
composer install vendor/bin/pest
Releasing a version
vendor/bin/pest # all green first git tag v1.0.0 # semantic versioning: v1.0.1 fixes, v1.1.0 features, v2.0.0 breaking git push origin main --tags
Games pick the new version up with composer update jemgames/game-auth. The JEM Games SSO repository
uses this checkout directly (a Composer path repository at ../JEMGamesSSOClient), so its
studio-auth tests and end-to-end suite always run against the current code here.