# Access tokens

> Require a token signed by your backend before a player can connect.

Source: https://syncverse.aqaddoura.com/docs/access-tokens

## When you need them

By default a game connects with its App ID alone. That is enough for prototypes and jams, but anyone who has your build has the App ID. Switch on **Require token** in the project settings and every connection must also carry a token that your backend signed. Tokens also let you fix a player's identity and restrict them to one room.

## Create an API key

In the dashboard open **API keys** and create a key. The secret is shown once; store it on your server only, never in the game build. You can have several keys and revoke any of them.

## Mint tokens on your backend

`@syncverse/server-sdk` has no dependencies and runs on Node 18 or newer.

```bash
npm install @syncverse/server-sdk
```

**server.ts**

```ts
import express from "express";
import { AccessToken } from "@syncverse/server-sdk";

const app = express();

// Your own login decides who gets a token.
app.post("/syncverse-token", requireYourLogin, (req, res) => {
    const token = new AccessToken(process.env.SYNCVERSE_API_KEY!, process.env.SYNCVERSE_API_SECRET!, {
        identity: req.user.id,       // becomes the player's default nickname
        name: req.user.displayName,  // optional
        // room: "match-42",         // optional: only this room may be created or joined
        ttlSeconds: 600,             // checked when the game connects
    });
    res.json({ token: token.toJwt() });
});
```

A token is a standard HS256 JWT: `iss` is the API key id, `sub` the identity, plus optional `name` and `room`, and `iat` / `exp`. Any JWT library can make one.

## Use it in Unity

```csharp
// Simplest: you already have the token.
master.AuthToken = token;
master.Connect ();

// Or let the SDK ask for one before every cloud connection.
master.TokenProvider = done => StartCoroutine (FetchToken (done));

IEnumerator FetchToken (Action<string> done) {
    using var req = UnityWebRequest.PostWwwForm ("https://your-backend.example/syncverse-token", "");
    yield return req.SendWebRequest ();
    var ok = req.result == UnityWebRequest.Result.Success;
    done (ok ? JsonUtility.FromJson<TokenReply> (req.downloadHandler.text).token : null);
}

[Serializable] class TokenReply { public string token; }
```

A missing token is refused with `TokenRequired`, a bad or expired one with `InvalidToken`. See [Connecting](https://syncverse.aqaddoura.com/docs/connecting) for how refusals reach your code.

> A token restricted to a room can only create or look up that room by name, and `JoinRandomRoom` answers `NotAllowed`.
