Skip to content
ZokoGames

Log in

User module

User module

SDK.user exposes who is playing. Players may be signed in to ZokoGames or anonymous guests; your game must work for both.

System information#

readonly isUserAccountAvailable: boolean
readonly systemInfo: SystemInfo

isUserAccountAvailable is false when the game is embedded somewhere without portal accounts. Hide sign-in UI when it is.

interface SystemInfo {
  countryCode: string;                       // "US"
  locale: string;                            // "en-US"
  device: { type: "desktop" | "tablet" | "mobile" };
  os: { name: string; version: string };
  browser: { name: string; version: string };
  applicationType: "web" | "pwa" | "google_play_store" | "apple_store";
}

Use device.type to decide on mobile controls, not "ontouchstart" in window, and locale to pick a language. See control pitfalls.

getUser#

getUser(): Promise<PortalUser | null>

interface PortalUser {
  username: string;
  profilePictureUrl: string;
  __dangerousUserId: string;
}

Returns the signed-in player or null. The double-underscore name is deliberate: __dangerousUserId comes from the browser, so anyone can fake it. Use it for display and local state only, and never to decide whose save to load on your server. Server-side identity comes from the token.

Update stored usernames and avatars whenever you see them change.

Friends#

listFriends(options: { page: number; size: number }): Promise<FriendsPage>

interface FriendsPage { friends: Friend[]; page: number; size: number; hasMore: boolean; total: number }
interface Friend { id: string; username: string; profilePictureUrl: string }

page starts at 1 and size is 1 to 50 (the portal caps it at 50). Only one request may run at a time (requestInProgress) and calls closer than 250 ms apart fail with rateLimited. Guests get userNotAuthenticated.

let page = 1, more = true;
while (more) {
  const res = await SDK.user.listFriends({ page, size: 20 });
  render(res.friends);
  more = res.hasMore;
  page++;
  await new Promise((r) => setTimeout(r, 300));
}

Tokens#

getUserToken(options?: { signingKeyType?: "IN_GAME_AUTH" | "IN_GAME_AUTH_LEGACY" }): Promise<string>

Returns a signed JWT that proves the player's identity to your server. It is valid for one hour. The SDK caches it and fetches a new one when less than a minute of life remains, so call it freely before each backend request. Without a signed-in player it rejects with userNotAuthenticated: let that player continue as a guest.

The signingKeyType option is accepted so code ported from other portals keeps working, but ZokoGames signs every token the same way: with one RS256 key. IN_GAME_AUTH and IN_GAME_AUTH_LEGACY return equivalent tokens, so there is nothing to migrate and new games should omit the option.

The token is a JWT signed with RS256. Its header carries alg: "RS256", typ: "JWT" and a kid that names the signing key. It carries these claims, plus iat (issue time) and exp (iat plus 3,600 seconds):

Claim Meaning
userId Stable player id. Use it as the key of your own account record.
gameId Your game's id. Check it matches, otherwise a token minted for another game could be replayed against yours.
username Display name at the time of issue.
profilePictureUrl Avatar URL at the time of issue.

Verifying on your server#

Never trust a token you did not verify, and never act on getUser() data sent from the browser. Fetch the public keys from the JWKS endpoint and verify the signature and expiry:

https://zokogames.com/.well-known/jwks.json

The key set is a standard JWKS with RS256 signature keys (use: "sig"). Cache it (an hour is fine) and refresh it when you see an unknown kid.

import { createRemoteJWKSet, jwtVerify } from "jose";

const JWKS = createRemoteJWKSet(new URL("https://zokogames.com/.well-known/jwks.json"));
const GAME_ID = process.env.ZOKO_GAME_ID;

export async function verifyZokoToken(token) {
  const { payload } = await jwtVerify(token, JWKS, { clockTolerance: 5 });
  if (payload.gameId !== GAME_ID) throw new Error("token is for a different game");
  return { userId: payload.userId, username: payload.username };
}
import os
import jwt  # PyJWT >= 2.8, with the "crypto" extra

jwks_client = jwt.PyJWKClient("https://zokogames.com/.well-known/jwks.json", cache_keys=True)
GAME_ID = os.environ["ZOKO_GAME_ID"]

def verify_zoko_token(token: str) -> dict:
    signing_key = jwks_client.get_signing_key_from_jwt(token)
    claims = jwt.decode(
        token,
        signing_key.key,
        algorithms=["RS256"],
        options={"require": ["exp", "iat"]},
        leeway=5,
    )
    if claims.get("gameId") != GAME_ID:
        raise ValueError("token is for a different game")
    return claims
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;

public sealed class ZokoTokenVerifier
{
    private static readonly HttpClient Http = new();
    private JsonWebKeySet? _keys;
    private DateTime _fetched = DateTime.MinValue;

    public async Task<JwtSecurityToken> VerifyAsync(string token, string gameId)
    {
        if (_keys is null || DateTime.UtcNow - _fetched > TimeSpan.FromHours(1))
        {
            var json = await Http.GetStringAsync("https://zokogames.com/.well-known/jwks.json");
            _keys = new JsonWebKeySet(json);
            _fetched = DateTime.UtcNow;
        }

        var parameters = new TokenValidationParameters
        {
            IssuerSigningKeys = _keys.GetSigningKeys(),
            ValidateIssuer = false,
            ValidateAudience = false,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.FromSeconds(5),
        };

        new JwtSecurityTokenHandler().ValidateToken(token, parameters, out var validated);
        var jwt = (JwtSecurityToken)validated;
        if (jwt.Claims.FirstOrDefault(c => c.Type == "gameId")?.Value != gameId)
            throw new SecurityTokenException("token is for a different game");
        return jwt;
    }
}

Send the token with each request, for example Authorization: Bearer <token>:

const token = await SDK.user.getUserToken();
const res = await fetch("https://api.example.com/save", {
  method: "POST",
  headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
  body: JSON.stringify(saveGame),
});
Warning

Local mode issues an unsigned token (alg: none). A correct verifier rejects it. For local backend development, add a clearly separated test-only bypass that is impossible to enable in production.

Sign-in prompt#

showAuthPrompt(): Promise<PortalUser>
addAuthListener(fn: (user: PortalUser) => void): void
removeAuthListener(fn: (user: PortalUser) => void): void

Opens the portal's sign-in dialog. Only call it in response to a player action, such as pressing a "Sign in to save your progress" button, never automatically at start. It resolves with the new user, or rejects:

Code Meaning
userAlreadySignedIn Someone is already signed in. Check with getUser() first.
showAuthPromptInProgress The dialog is already open.
userCancelled The player closed it. Carry on as a guest.

The auth listener also fires when the player signs in through the portal's own header while your game is open, so register one and update your UI there instead of relying only on the promise.

SDK.user.addAuthListener((user) => { hud.setName(user.username); syncProgress(); });

signInButton.onclick = async () => {
  try { await SDK.user.showAuthPrompt(); }
  catch (e) { if (e.code !== "userCancelled") console.warn(e.code); }
};

Account linking#

showAccountLinkPrompt(): Promise<{ response: "yes" | "no" }>

For games with their own accounts. Ask a signed-in player whether to link their ZokoGames identity to the game's existing account. Link the userId from the verified token on your server only when the response is "yes", and prefer linking to fresh accounts over merging two accounts with progress. A player with no signed-in portal user gets userNotAuthenticated. See account integration scenarios.

Submitting scores#

SDK.user.submitScore({ encryptedScore, score }) posts a leaderboard score from the client. It is documented with its encryption scheme in leaderboards.

Something unclear, wrong or missing on this page? Tell us through support · Test your game in the preview tool