# Authentication

URL: https://docs.folkways.io/docs/realtime-api/authentication

Token claims, signing rules, service tokens and publishable keys, and how to sign a token in any language.

Every request to the Realtime API carries a token: in the `Hello` frame on a WebSocket, in
`Authorization: Bearer <token>` on HTTP. Never put a token in a URL. [Identities and tokens](/docs/concepts/authentication)
explains the model; this page is the exact contract.

## Token format [#token-format]

A JWT signed with one of the segment's [signing keys](/docs/console/signing-keys).

**Header**

| Field | Value |
| --- | --- |
| `alg` | `EdDSA` (Ed25519) or `ES256` (P-256), matching the key. The algorithm is taken from the key, never trusted from the token |
| `kid` | The signing key's ID |

**Claims**

| Claim | Required | Meaning |
| --- | --- | --- |
| `seg` | yes | The segment ID |
| `sub` | yes, unless anonymous | The identity, at most 256 bytes. Must not start with `anon:`. Make it one topic level (no `/`) if the user needs a [personal topic](/docs/concepts/topics#personal-topics) or presence |
| `kind` | no | `user` (default), `agent`, `service` or `anonymous`. Anonymous tokens have no `sub` |
| `cap` | no | Capabilities: `[{ "topic": "<pattern>", "ops": ["subscribe", …] }]`. Empty: the token can connect and nothing else |
| `iat` | yes | Issued at, Unix seconds |
| `exp` | yes | Expiry, Unix seconds, **at most 15 minutes in the future** |
| `nbf` | no | Not before, Unix seconds |
| `jti` | no | A unique token ID. Without one the token can't be [revoked](/docs/realtime-api/kick-and-revoke) |
| `presence` | no | `false` keeps the connection out of presence (it is invisible). Default `true` |

Thirty seconds of clock skew are tolerated on `exp`, `nbf` and `iat`.

Ops in `cap` are `subscribe`, `publish`, `set`, `signal`, `presence` and `history`; see
[Capabilities](/docs/concepts/authentication#capabilities). Patterns use `*` for one level and a trailing `>` for one
or more.

<Callout title="topic, not topics">
  In the JWT, each capability has a `topic` field holding one pattern. The JavaScript SDK's `createToken()` takes
  the same thing as `topics`; it writes `topic` into the token for you.
</Callout>

## Sign a token [#sign-a-token]

Any JWT library that supports EdDSA or ES256 works.

<Tabs items={['Node.js (SDK)', 'Node.js (jose)', 'Python', 'Go']}>
  <Tab value="Node.js (SDK)">
    ```ts
    import { Folkways } from '@folkwaysio/realtime/server';

    const folkways = new Folkways.Rest({ url, segment, signingKey: { kid, privateKey } });
    const { token, jti, expiresAt } = await folkways.createToken({
      identity: 'user:42',
      capabilities: [{ topics: 'rooms/42', ops: ['subscribe', 'publish'] }],
    });
    ```
  </Tab>
  <Tab value="Node.js (jose)">
    ```js
    import { SignJWT, importPKCS8 } from 'jose';

    const key = await importPKCS8(process.env.FOLKWAYS_PRIVATE_KEY, 'EdDSA');
    const token = await new SignJWT({
      seg: process.env.FOLKWAYS_SEGMENT_ID,
      kind: 'user',
      cap: [{ topic: 'rooms/42', ops: ['subscribe', 'publish'] }],
    })
      .setProtectedHeader({ alg: 'EdDSA', kid: process.env.FOLKWAYS_KEY_ID })
      .setSubject('user:42')
      .setJti(crypto.randomUUID())
      .setIssuedAt()
      .setExpirationTime('10m')
      .sign(key);
    ```
  </Tab>
  <Tab value="Python">
    ```python
    import os, time, uuid
    import jwt  # PyJWT with the cryptography package

    now = int(time.time())
    token = jwt.encode(
        {
            "seg": os.environ["FOLKWAYS_SEGMENT_ID"],
            "sub": "user:42",
            "kind": "user",
            "cap": [{"topic": "rooms/42", "ops": ["subscribe", "publish"]}],
            "iat": now,
            "exp": now + 600,
            "jti": str(uuid.uuid4()),
        },
        open(os.environ["FOLKWAYS_PRIVATE_KEY_FILE"]).read(),
        algorithm="EdDSA",
        headers={"kid": os.environ["FOLKWAYS_KEY_ID"]},
    )
    ```
  </Tab>
  <Tab value="Go">
    ```go
    // github.com/golang-jwt/jwt/v5
    now := time.Now()
    claims := jwt.MapClaims{
        "seg":  os.Getenv("FOLKWAYS_SEGMENT_ID"),
        "sub":  "user:42",
        "kind": "user",
        "cap":  []map[string]any{{"topic": "rooms/42", "ops": []string{"subscribe", "publish"}}},
        "iat":  now.Unix(),
        "exp":  now.Add(10 * time.Minute).Unix(),
        "jti":  uuid.NewString(),
    }
    t := jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims)
    t.Header["kid"] = os.Getenv("FOLKWAYS_KEY_ID")
    token, err := t.SignedString(privateKey) // an ed25519.PrivateKey
    ```
  </Tab>
</Tabs>

The segment's **Connect** tab in the Console has these examples filled in with its own values.

## Service tokens [#service-tokens]

A token with `"kind": "service"` is for your backend. Besides publishing, it is what the backend endpoints take:

| To | The service token needs |
| --- | --- |
| Write to `$user/{identity}` | `publish` on `$user/{identity}`, or on `$user/>` |
| [Open a DM](/docs/realtime-api/dm-open) | `publish` on the room (e.g. `dm/>`) and on every member's `$user/{identity}` |
| [Manage a private topic's members](/docs/realtime-api/members) | `publish` on the topic |
| [Kick an identity](/docs/realtime-api/kick-and-revoke) | `publish` on that identity's `$user/{identity}` |
| [Revoke a token](/docs/realtime-api/kick-and-revoke) | `publish` on `$user/>` |

Service tokens need no member entry on private topics. Sign them only on your servers.

## Anonymous tokens [#anonymous-tokens]

An anonymous token has `"kind": "anonymous"` and no `sub`. The segment must allow anonymous connections, or the
token is refused with `AuthInvalid`. Give anonymous tokens narrow rights, typically `subscribe` on public topics.
Your backend can sign one, or an app can get one for a [publishable key](/docs/realtime-api/token).

## Failures [#failures]

| Code | When |
| --- | --- |
| `AuthRequired` | No token |
| `AuthInvalid` | Bad signature, unknown `kid`, wrong segment, malformed claims, a lifetime over 15 minutes, an anonymous token where they aren't allowed |
| `AuthExpired` | The token has expired. Get a new one |
| `AuthRevoked` | The token was revoked, or the identity was kicked. Don't retry with it |
| `Suspended` | The segment is off, or the workspace's package isn't active |
