Player token: signing players in to your game server
A game with its own server (multiplayer, its own account, a server-side economy) needs to know which
portal player came to the server. player.id is not good for this: the pseudonym is public — it
shows in leaderboards, and anyone can pretend to be another player. The portal gives the game a signed
player token; your server checks the signature against the portal's public keys without calling us
on every sign-in. Add the server addresses to the game network first.
Getting a token
SDK 1.1: InstaPlay.player.getToken() (reference).
if (InstaPlay.isSupported('token')) {
const token = await InstaPlay.player.getToken()
const res = await fetch('https://api.my-game.example/session', {
method: 'POST',
headers: { authorization: `Bearer ${token}` },
})
const { session } = await res.json() // your server's own session — use it from now on
}
- A token lives 10 minutes. The SDK caches it until the end of its lifetime minus a minute and does not call the portal on every call; parallel calls share one request.
- Exchange the token for your own session once at sign-in — do not send it with every request.
- No
tokenfeature (outside the portal,localmode, no session) —not_supported; the portal is unavailable or the game is hidden —unavailable; more than 10 calls a minute —rate_limited. - In preview the token
audispreview:<game id>, and a production server rejects it: run the test server for previews withINSTAPLAY_ACCEPT_PREVIEW=1, as in the examples below (preview and test server). - Engines: Unity —
InstaPlay.Player.GetToken, Godot —await InstaPlay.player_get_token(), Construct —await InstaPlayC3.getToken()(Unity, Godot, Construct 3).
What is inside
A JWT signed with ES256. Header: alg: ES256, typ: ip-player+jwt, kid — the signing key.
| Claim | Value |
|---|---|
iss |
the portal address, https://instaplay.ru |
aud |
the game id from the dashboard (not the slug — it changes); in preview — preview:<game id> |
sub |
the player pseudonym for your studio — the same player.id, p + 20 characters [a-z2-7] |
kind |
guest or account |
iat, exp |
issued and expires: exp = iat + 600 |
jti |
a unique token id — lets you forbid reuse |
merged |
optional: up to 3 pseudonyms of guests merged into this account within 7 days (below) |
There is no nickname, avatar, email, country or account id in the token. Games of one studio see the
player with the same sub; aud tells the games apart.
Required checks
- The algorithm is strictly
ES256, not taken from the token header (a swap tononeorHS256). typisip-player+jwt: other portal JWTs with the sameissdo not pass as a player token.issis the portal;audis your game id (on a test server — alsopreview:<id>).exp— with no more than 30 seconds of tolerance.submatches^p[a-z2-7]{20}$.- JWKS keys come from a cache no older than 10 minutes; an unknown
kidreloads the set (at most once per 30 seconds).
Recommended: keep jti until exp and do not accept it twice.
Keys and JWKS caching
Public keys — GET https://instaplay.ru/.well-known/instaplay-jwks.json (a standard JWKS, EC P-256
keys). The response is cacheable: Cache-Control: public, max-age=300, stale-while-revalidate=300.
- Cache the set on your server for no longer than 10 minutes and reload it on an unknown
kid. All examples below do so; the lifetime comes fromINSTAPLAY_JWKS_TTL(seconds, 600 by default). - Planned rotation: a new key appears in the set at least 2 hours before it starts signing; the old key stays in the set while its tokens live. A server with a cache of 10 minutes or less does not notice the rotation.
- If a key is compromised, the portal removes it from the set at once. A server that keeps to the cache lifetime stops accepting tokens signed with it within 20 minutes; a server with a longer cache accepts forgeries longer — that is its risk.
Node.js
// Node.js 22 (jose >= 5) — verifying an InstaPlay player token on the game server.
// Addresses come from env (the live portal by default); the emulator and tests set their own.
import { createRemoteJWKSet, jwtVerify } from 'jose'
const ISSUER = process.env.INSTAPLAY_ISSUER ?? 'https://instaplay.ru'
const JWKS_URL = process.env.INSTAPLAY_JWKS_URL ?? `${ISSUER}/.well-known/instaplay-jwks.json`
const TTL_MS = Number(process.env.INSTAPLAY_JWKS_TTL ?? 600) * 1000 // ≤ 10 min
const JWKS = createRemoteJWKSet(new URL(JWKS_URL), {
cacheMaxAge: TTL_MS,
cooldownDuration: 30_000, // unknown kid → reload, at most once per 30 s
})
const AUDIENCE = [process.env.INSTAPLAY_GAME_ID]
if (process.env.INSTAPLAY_ACCEPT_PREVIEW === '1') AUDIENCE.push(`preview:${AUDIENCE[0]}`) // test server only
export async function playerFrom(token) {
const { payload } = await jwtVerify(token, JWKS, {
issuer: ISSUER,
audience: AUDIENCE,
typ: 'ip-player+jwt',
algorithms: ['ES256'],
clockTolerance: 30,
})
if (typeof payload.sub !== 'string' || !/^p[a-z2-7]{20}$/.test(payload.sub)) {
throw new Error('bad sub')
}
return { id: payload.sub, kind: payload.kind, merged: payload.merged ?? [] }
}
Ruby
# Ruby (gem "jwt" >= 2.7) — verifying an InstaPlay player token on the game server (ADR-0017 §6).
# Addresses come from env (the live portal by default); CI tests point them to the emulator and shorten the TTL.
require 'jwt'; require 'net/http'; require 'json'
ISSUER = ENV.fetch('INSTAPLAY_ISSUER', 'https://instaplay.ru')
JWKS_URL = URI(ENV.fetch('INSTAPLAY_JWKS_URL', "#{ISSUER}/.well-known/instaplay-jwks.json"))
JWKS_TTL = Integer(ENV.fetch('INSTAPLAY_JWKS_TTL', '600')) # ≤ 10 min: a removed key stops being accepted
JWKS_LOADER = lambda do |opts|
age = @jwks_at ? Time.now - @jwks_at : Float::INFINITY
if age > JWKS_TTL || (opts[:kid_not_found] && age > 30) # unknown kid → reload, at most once per 30 s
@jwks = JWT::JWK::Set.new(JSON.parse(Net::HTTP.get(JWKS_URL)))
@jwks_at = Time.now
end
@jwks
end
AUDIENCE = [ENV.fetch('INSTAPLAY_GAME_ID')]
AUDIENCE << "preview:#{AUDIENCE[0]}" if ENV['INSTAPLAY_ACCEPT_PREVIEW'] == '1' # test server only
def player_from(token)
payload, header = JWT.decode(token, nil, true, algorithms: ['ES256'], jwks: JWKS_LOADER,
iss: ISSUER, verify_iss: true, aud: AUDIENCE, verify_aud: true, leeway: 30)
raise 'bad typ' unless header['typ'] == 'ip-player+jwt'
raise 'bad sub' unless payload['sub'].match?(/\Ap[a-z2-7]{20}\z/)
payload
end
Python
# Python (PyJWT[crypto] >= 2.8) — verifying an InstaPlay player token on the game server (ADR-0017 §6).
# Addresses come from env (the live portal by default); CI tests point them to the emulator and shorten the TTL.
import os, re, time, urllib.request, jwt
ISSUER = os.environ.get("INSTAPLAY_ISSUER", "https://instaplay.ru")
JWKS_URL = os.environ.get("INSTAPLAY_JWKS_URL", f"{ISSUER}/.well-known/instaplay-jwks.json")
TTL = int(os.environ.get("INSTAPLAY_JWKS_TTL", "600")) # ≤ 10 min: a removed key stops being accepted
_jwks, _jwks_at = {}, float("-inf")
def signing_key(kid):
global _jwks, _jwks_at
age = time.monotonic() - _jwks_at
if age > TTL or (kid not in _jwks and age > 30): # unknown kid → reload, at most once per 30 s
with urllib.request.urlopen(JWKS_URL, timeout=5) as res:
_jwks = {k.key_id: k.key for k in jwt.PyJWKSet.from_json(res.read().decode()).keys}
_jwks_at = time.monotonic()
return _jwks[kid]
AUDIENCE = [os.environ["INSTAPLAY_GAME_ID"]]
if os.environ.get("INSTAPLAY_ACCEPT_PREVIEW") == "1": # test server only
AUDIENCE.append(f"preview:{AUDIENCE[0]}")
def player_from(token: str) -> dict:
header = jwt.get_unverified_header(token)
if header.get("typ") != "ip-player+jwt":
raise ValueError("bad typ")
payload = jwt.decode(token, signing_key(header.get("kid")), algorithms=["ES256"],
issuer=ISSUER, audience=AUDIENCE, leeway=30)
if not re.fullmatch(r"p[a-z2-7]{20}", payload["sub"]):
raise ValueError("bad sub")
return payload
Environment variables of the examples: INSTAPLAY_GAME_ID — the game id from the dashboard (required),
INSTAPLAY_ISSUER and INSTAPLAY_JWKS_URL — the portal or the emulator,
INSTAPLAY_JWKS_TTL — key cache lifetime, INSTAPLAY_ACCEPT_PREVIEW=1 — accept preview tokens. These
three examples run in our tests against the emulator's signer: a live token is accepted, a preview token
is accepted with the added audience, a token with a foreign typ is rejected, and a token of a key
removed from the set is rejected after the cache lifetime.
Preview and test server
In preview a token has aud = preview:<game id>, kind: guest, and sub is a tester
pseudonym of the same p… format; it is also the game's player.id. A production server checking aud
rejects such a token by itself. To let the moderator and testers play, a test server adds
preview:<id> to the accepted audiences (INSTAPLAY_ACCEPT_PREVIEW=1) — preferably with separate data:
testers never collide with live players, but they live in the same schema. A submission is reviewed
against the server from its network — say in the note which server accepts preview tokens.
A guest became an account
A guest who signs in to an existing account is merged into it: sub changes to the account pseudonym,
and for 7 days merged carries the previous guest pseudonyms (up to the 3 newest). Find the guest's
progress on your server by them and move it to the account on the first sign-in. A guest who signs up
for a new account keeps the pseudonym — merged is empty.
Emulator
instaplay dev issues tokens with its own dev key (CLI): JWKS —
http://localhost:4300/_emu/jwks.json, iss — the emulator origin, aud — --game-id <dashboard id>
or dev:<game slug>, sub — player.id of the panel player. The emulator prints these values at start —
pass them to your local game server as INSTAPLAY_ISSUER, INSTAPLAY_JWKS_URL and INSTAPLAY_GAME_ID.
The panel switches the token mode — “issued”, “unavailable” (not_supported) or “expired” (exp in the
past): check how your server handles errors.
Player change
If the player signs in or out in another tab, about 1.5 seconds before the restart the game gets the
playerChanging event (events). In this window getToken() returns the
previous player's still valid token from the cache — send that player's data to your server. Portal
saves are unavailable in this window. After the restart the token belongs to the new player. A sign-in
from the game itself (player.login(), SDK 1.4) works differently: the first sign-in upgrades the guest
in place without a restart (the same sub, kind becomes account), and on a sign-in to another
account the token cache is dropped at once — send data with your server's session
(player and sign-in).