# Sign playback tokens

Let your backend decide who watches a private video, with a token it signs itself.

Source: https://clipmux.com/docs/build/play/sign-tokens

A private video plays only with a token: a short JWT that your backend signs
with your app's signing key after it has decided the viewer may watch. Signing
is local. Your backend makes no call to ClipMux per play, and ClipMux checks
the signature when the player asks for the video.

If you use `clipmuxHandler` and `<clipmux-player session-url>` from the
[quickstart](/docs/build/quickstart), this already happens: your `playback`
callback decides, and the handler signs. Read on to sign tokens yourself, for
your own route, another player or another language.

## Before you start [#before-you-start]

- A video with a **signed** playback ID. Uploads are signed unless you ask
  for `playback_policy: "public"`.
- Your app's signing key, as `CLIPMUX_SIGNING_KID` (the key's ID) and
  `CLIPMUX_SIGNING_KEY` (a P-256 private key in PEM).
  `npx @clipmux/node init` writes both. You can also create one under
  **Apps & API** in the dashboard, or with `clipmux admin create-signing-key`
  on the server.
- The media origin, `base_url`, from `GET /v1/app`, for example
  `https://media.example.com`.

<Warning>
The signing key is a secret. Keep it on your server, never in browser code,
and never in a log.
</Warning>

## What a token holds [#what-a-token-holds]

A token is an ES256 JWT. Its header names the key, and its claims name the
video, what the token may fetch, and for how long.

| Part | Field | Value |
| --- | --- | --- |
| Header | `alg` | `ES256` |
| Header | `kid` | Your `CLIPMUX_SIGNING_KID` |
| Claims | `sub` | The playback ID, `pid_…` |
| Claims | `aud` | `v` to play the video, its tracks and its poster; `t` for the poster only |
| Claims | `iat`, `exp` | Issued and expiry times, in whole Unix seconds |
| Claims | `vid` | Optional. A stable ID for the viewer, which counts unique viewers. ClipMux stores only a keyed hash of it |

`exp - iat` may be at most `max_token_lifetime_seconds` from `GET /v1/app`,
which is 7 days by default. Keep tokens short, 15 minutes for a player that
renews them, and let the player ask again.

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

<Steps>
<Step>
### Check access [#check-access]

Decide in your own code, from your own session, whether this person may watch
this video. ClipMux has no idea who your users are. If the answer is no,
don't sign anything.
</Step>

<Step>
### Sign [#sign]

<Tabs items={["Node","Python","Go","PHP"]}>
<Tab value="Node">
```ts title="playback.ts"
import { ClipMux } from '@clipmux/node'

const clipmux = new ClipMux() // reads the CLIPMUX_* settings

const token = await clipmux.playback.token('pid_…', {
  viewerId: user.id, // optional
  expiresIn: '15m', // the default
})
```

`{ audience: 'poster' }` signs a poster-only token.
</Tab>

<Tab value="Python">
```python title="playback_token.py"
import time

import jwt  # pip install "pyjwt[crypto]"

def playback_token(
    playback_id: str,
    signing_key_pem: str,
    kid: str,
    viewer_id: str | None = None,
    audience: str = "v",
    ttl: int = 900,
) -> str:
    """A token for a signed playback ID, signed with your app's signing key.

    signing_key_pem is CLIPMUX_SIGNING_KEY and kid is CLIPMUX_SIGNING_KID.
    audience is "v" to play, or "t" for the poster. viewer_id, when given,
    counts unique viewers; ClipMux keeps only a keyed hash of it.
    """
    now = int(time.time())
    claims = {"sub": playback_id, "aud": audience, "iat": now, "exp": now + ttl}
    if viewer_id:
        claims["vid"] = viewer_id
    return jwt.encode(claims, signing_key_pem, algorithm="ES256", headers={"kid": kid})
```
</Tab>

<Tab value="Go">
```go title="playback_token.go"
package clipmux

import (
	"crypto/ecdsa"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

// PlaybackToken signs a token for a signed playback ID with your app's
// signing key: CLIPMUX_SIGNING_KEY, read once with
// jwt.ParseECPrivateKeyFromPEM, and CLIPMUX_SIGNING_KID. audience is "v" to
// play, or "t" for the poster. viewerID may be empty; when set it counts
// unique viewers, and ClipMux keeps only a keyed hash of it.
func PlaybackToken(key *ecdsa.PrivateKey, kid, playbackID, viewerID, audience string, ttl time.Duration) (string, error) {
	now := time.Now()
	claims := jwt.MapClaims{"sub": playbackID, "aud": audience, "iat": now.Unix(), "exp": now.Add(ttl).Unix()}
	if viewerID != "" {
		claims["vid"] = viewerID
	}
	t := jwt.NewWithClaims(jwt.SigningMethodES256, claims)
	t.Header["kid"] = kid
	return t.SignedString(key)
}
```
</Tab>

<Tab value="PHP">
```php title="playback_token.php"
<?php

use Firebase\JWT\JWT; // composer require firebase/php-jwt

/**
 * A token for a signed playback ID, signed with your app's signing key.
 *
 * $signingKeyPem is CLIPMUX_SIGNING_KEY and $kid is CLIPMUX_SIGNING_KID.
 * $audience is "v" to play, or "t" for the poster. $viewerId, when given,
 * counts unique viewers; ClipMux keeps only a keyed hash of it.
 */
function clipmux_playback_token(
    string $playbackId,
    string $signingKeyPem,
    string $kid,
    ?string $viewerId = null,
    string $audience = 'v',
    int $ttl = 900,
): string {
    $now = time();
    $claims = ['sub' => $playbackId, 'aud' => $audience, 'iat' => $now, 'exp' => $now + $ttl];
    if ($viewerId !== null && $viewerId !== '') {
        $claims['vid'] = $viewerId;
    }
    return JWT::encode($claims, $signingKeyPem, 'ES256', $kid);
}
```
</Tab>
</Tabs>

Any ES256 JWT library works in other languages: put `kid` in the header and
the claims above in the body.
</Step>

<Step>
### Play [#play]

Give the player the token, or build the URL yourself:

```txt
https://media.example.com/v/{token}/{playback_id}/master.m3u8
https://media.example.com/v/{token}/{playback_id}/poster.jpg
```

With `<clipmux-player>`, set `getToken` so the player asks your backend each
time it needs a fresh token. See [Add the player](/docs/build/play/player).
</Step>
</Steps>

## Check it works [#check-it-works]

```bash
curl -s -o /dev/null -w '%{http_code}\n' \
  "https://media.example.com/v/$TOKEN/pid_…/master.m3u8"
```

- `200`: the token is good.
- `401` with `token_expired`: the token's `exp` has passed. Sign a new one;
  the player does this by itself.
- `403` with `denied`: the signature, the key, the playback ID or the
  audience is wrong, or the key was revoked. Stop, and check the `kid`
  matches the key you signed with.
- `404`: the playback ID was revoked, or doesn't exist.

## Safari and AirPlay [#safari-and-airplay]

iOS before 17.1 and AirPlay play HLS themselves and can't renew a token
mid-video. `<clipmux-player>` tells your backend when it plays natively:
`native: true` in the session request, or in `getToken`'s argument. Sign
those tokens for longer. The Node SDK does it for you with
`playback.token(id, { native: true, durationSeconds })`: the larger of twice
the video's duration and 4 hours, or 12 hours without a duration, within the
maximum.

## Next [#next]

- [Add the player](/docs/build/play/player)
- [Posters and thumbnails](/docs/build/play/posters-and-thumbnails)
- [Playback IDs and tokens](/docs/build/concepts/playback-ids-and-tokens),
  the concepts behind them
