> For the complete documentation index, see [llms.txt](https://clients.medianova.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://clients.medianova.com/products/security/auth-token-2-0.md).

# Auth Token 2.0

Protect CDN-delivered content using signed, time-limited URLs that restrict access to authorized viewers.

**Auth Token 2.0** allows you to control access to protected CDN content by requiring a valid cryptographic token in each request URL. Tokens are generated by your application and validated at the Medianova edge before content is delivered.

Auth Token 2.0 supports both query string and path-based token placement, making it suitable for protecting video streams, private downloads, subscriber-only content, and other resources that require controlled access.

{% hint style="info" %}
Auth Token 2.0 is enabled by Medianova upon customer request.

Contact [**Medianova Support**](https://clients.medianova.com/support-and-troubleshooting/contacting-customer-support.md) to activate the feature for your hostname and specify which paths should be protected.
{% endhint %}

## How Auth Token 2.0 Works

Auth Token 2.0 uses HMAC-SHA256 signatures to verify that a request is authorized.

1. Your application generates a token using a shared secret key, an expiration time, and the path being authorized.
2. The token is included in the request URL, either as a query string parameter or as part of the URL path.
3. The viewer requests the protected content through Medianova CDN.
4. The CDN validates the token signature, expiration time, authorized path, and optional IP restriction.
5. If validation succeeds, the content is delivered. Otherwise, the request returns `403 Forbidden`.

Token validation is performed at the edge without storing individual tokens. This allows consistent validation across Medianova Points of Presence (POPs).

## Before You Begin

Before generating tokens:

* Contact Medianova Support to enable Auth Token 2.0 for your hostname.
* Specify the paths that require protection, such as `/protected/*`.
* Obtain the shared secret key associated with your Auth Token 2.0 configuration.
* Confirm whether your hostname uses query string mode or path mode.
* Ensure your application can generate HMAC-SHA256 signatures.

The shared secret key is a 64-character hexadecimal string representing 32 bytes.

{% hint style="info" %}
Keep the shared secret key on your application server. Never expose it in browser code, mobile applications, client-side players, public repositories, or logs.
{% endhint %}

## Token Format

An Auth Token 2.0 consists of `name=value` fields separated by the tilde character (`~`), followed by an HMAC signature.

Example:

`exp=1893456000~acl=/videos/movie/*~hmac=<signature>`

### Supported Token Parameters

<table data-header-hidden><thead><tr><th width="141"></th><th width="132.5"></th><th></th></tr></thead><tbody><tr><td>Parameter</td><td>Required</td><td>Description</td></tr><tr><td><code>ip</code></td><td>No</td><td>Restricts token usage to a specific IPv4 or IPv6 address.</td></tr><tr><td><code>st</code></td><td>No</td><td>Token start time, expressed as a Unix timestamp in seconds.</td></tr><tr><td><code>exp</code></td><td>Yes</td><td>Token expiration time, expressed as a Unix timestamp in seconds.</td></tr><tr><td><code>acl</code></td><td>Conditional</td><td>Path or wildcard pattern authorized by the token. Use <code>acl</code> or <code>url</code>.</td></tr><tr><td><code>id</code></td><td>No</td><td>Session or user identifier included in the signature.</td></tr><tr><td><code>data</code></td><td>No</td><td>Additional application-defined data included in the signature.</td></tr><tr><td><code>hmac</code></td><td>Yes</td><td>HMAC-SHA256 signature represented as lowercase hexadecimal. Must be the final field.</td></tr></tbody></table>

When using `url` instead of `acl`, the `url` field is included in the signature calculation but is not included in the transmitted token.

### Signature Generation

To generate the signature:

1. Collect the applicable token parameters.
2. Arrange the fields in this order: `ip`, `st`, `exp`, `acl`, `id`, `data`.
3. Omit optional fields that are not used.
4. Join the fields using `~`.
5. If using `url` instead of `acl`, append `url=<path>` to the signing string.
6. Decode the hexadecimal shared key into raw bytes.
7. Calculate the HMAC-SHA256 signature.
8. Convert the result to lowercase hexadecimal and append it as `hmac`.

Example signing string:

`exp=1893456000~acl=/videos/movie/*`

{% hint style="info" %}
Parameter order is significant. Changing the order of signed fields produces a different signature and causes token validation to fail.
{% endhint %}

## Generate and Use a Auth Token 2.0

{% stepper %}
{% step %}

### Define the Protected Path

Choose the file or directory that the token should authorize.

| Use case              | Parameter | Example                |
| --------------------- | --------- | ---------------------- |
| Single protected file | `url`     | `/protected/movie.mp4` |
| HLS or DASH stream    | `acl`     | `/protected/movie/*`   |
| Protected directory   | `acl`     | `/downloads/user42/*`  |

The `*` wildcard matches characters including `/`, allowing one token to authorize multiple resources within a directory.
{% endstep %}

{% step %}

### Set the Expiration Time

Use the `exp` parameter to define when the token expires.

For example:

`exp=1893456000`

The value is a Unix timestamp in seconds.

For streaming applications, choose an expiration time that covers the expected viewing session.
{% endstep %}

{% step %}

### Generate the Signature

Generate an HMAC-SHA256 signature using your shared secret key and the selected token parameters.

Use one of the language-specific examples below.
{% endstep %}

{% step %}

### Add the Token to the Request URL

Auth Token 2.0 supports two URL placement modes.

#### **Query String Mode**

The token is passed as a query string parameter.

```
https://cdn.example.com/protected/movie.mp4?token=exp=1893456000~acl=/protected/movie.mp4~hmac=<hmac>
```

Query string mode is suitable for individual files and protected downloads.

#### **Path Mode**

The token is included directly in the URL path.

```
https://cdn.example.com/exp=1893456000~acl=/protected/movie/*~hmac=<hmac>/protected/movie/master.m3u8
```

Path mode is recommended for HLS and DASH streaming, where manifests reference additional media segments.

{% hint style="info" %}
The token placement mode is configured for your hostname. Contact Medianova Support to confirm which mode is enabled before generating production URLs.
{% endhint %}
{% endstep %}

{% step %}

### Verify Token Validation

After Auth Token 2.0 has been enabled, test access to a protected resource.

Before testing, replace `cdn.example.com` with your CDN hostname and `<hmac>` with a valid HMAC-SHA256 signature generated using your shared secret key.

Ensure that the token has not expired, the ACL matches the requested resource, and the token placement mode matches your hostname configuration.

The examples below assume that Auth Token 2.0 has been enabled in query string mode for the `/protected/video/*` path.

Request with a valid token:

```
curl -I "https://cdn.example.com/protected/video/seg1.ts?token=exp=1893456000~acl=/protected/video/*~hmac=<hmac>"
```

For an existing, accessible resource with a valid token, the expected response is `200 OK`. Depending on the resource and origin configuration, another successful HTTP status may be returned.

Request without a token:

```
curl -I "https://cdn.example.com/protected/video/seg1.ts"
```

Expected result:

`403 Forbidden`

Also verify that an expired token is rejected.
{% endstep %}
{% endstepper %}

## Code Examples

The following examples demonstrate how to generate Auth Token 2.0s using HMAC-SHA256.

Replace the example key and paths with the values associated with your configuration.

### Test Vector

Use the following values to verify that your implementation generates the expected signature.

<table data-header-hidden><thead><tr><th width="166.5"></th><th></th></tr></thead><tbody><tr><td>Input</td><td>Value</td></tr><tr><td>Key (hex)</td><td><code>00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff</code></td></tr><tr><td>Signed fields</td><td><code>exp=1893456000~acl=/videos/movie/*</code></td></tr><tr><td>Expected HMAC</td><td><code>f7804edd4d367aa03ce249b14a5233d038e6a55d6055b263152162255f25b02a</code></td></tr></tbody></table>

### Python

```
import os
import hmac
import hashlib
import time
import binascii

def generate_token(
    key_hex,
    window_seconds=None,
    exp=None,
    st=None,
    acl=None,
    url=None,
    ip=None,
    session_id=None,
    data=None
):
    if exp is None:
        exp = int((st or time.time()) + window_seconds)

    if not acl and not url:
        raise ValueError("set acl or url")

    fields = []

    if ip:
        fields.append(f"ip={ip}")

    if st is not None:
        fields.append(f"st={int(st)}")

    fields.append(f"exp={int(exp)}")

    if acl:
        fields.append(f"acl={acl}")

    if session_id:
        fields.append(f"id={session_id}")

    if data:
        fields.append(f"data={data}")

    to_sign = list(fields)

    if url and not acl:
        to_sign.append(f"url={url}")

    digest = hmac.new(
        binascii.unhexlify(key_hex),
        "~".join(to_sign).encode(),
        hashlib.sha256
    ).hexdigest()

    return "~".join(fields + [f"hmac={digest}"])

KEY_HEX = os.environ["MEDIANOVA_TOKEN_KEY"]

token = generate_token(
    KEY_HEX,
    window_seconds=3600,
    acl="/protected/movie/*"
)

print(token)
```

Set the `MEDIANOVA_TOKEN_KEY` environment variable to your Auth Token 2.0 shared key before running this example. The key must be a 64-character hexadecimal string.

{% hint style="info" %}
Save the Python example as `generate_token.py`, then set the environment variable and run the script using the commands for your operating system.
{% endhint %}

#### **Linux/macOS**

```
export MEDIANOVA_TOKEN_KEY="<your-64-character-hex-key>"
python3 generate_token.py
```

#### Windows PowerShell

```
$env:MEDIANOVA_TOKEN_KEY = "<your-64-character-hex-key>"
python generate_token.py
```

{% hint style="info" %}
For security, do not hardcode your production key or commit it to source control.
{% endhint %}

### Node.js

```
const crypto = require("crypto");

function generateToken({
  keyHex, exp, acl, url, ip, st, id, data
}) {
  if (!acl && !url) {
    throw new Error("set acl or url");
  }

  const fields = [];

  if (ip) fields.push(`ip=${ip}`);
  if (st) fields.push(`st=${st}`);

  fields.push(`exp=${exp}`);

  if (acl) fields.push(`acl=${acl}`);
  if (id) fields.push(`id=${id}`);
  if (data) fields.push(`data=${data}`);

  const toSign = (url && !acl)
    ? [...fields, `url=${url}`]
    : fields;

  const hmac = crypto
    .createHmac("sha256", Buffer.from(keyHex, "hex"))
    .update(toSign.join("~"))
    .digest("hex");

  return [...fields, `hmac=${hmac}`].join("~");
}
```

### PHP

```
<?php

function generate_token(
    $keyHex,
    $exp,
    $acl = null,
    $url = null,
    $ip = null
) {
    if (!$acl && !$url) {
        throw new Exception("set acl or url");
    }

    $fields = [];

    if ($ip) {
        $fields[] = "ip=$ip";
    }

    $fields[] = "exp=$exp";

    if ($acl) {
        $fields[] = "acl=$acl";
    }

    $toSign = ($url && !$acl)
        ? array_merge($fields, ["url=$url"])
        : $fields;

    $hmac = hash_hmac(
        "sha256",
        implode("~", $toSign),
        hex2bin($keyHex)
    );

    return implode(
        "~",
        array_merge($fields, ["hmac=$hmac"])
    );
}
```

### Bash and OpenSSL

```
KEY_HEX="<your 64-char hex key>"
EXP=$(( $(date +%s) + 3600 ))

FIELDS="exp=${EXP}~acl=/protected/movie/*"

HMAC=$(printf '%s' "$FIELDS" |
  openssl dgst -sha256 -mac HMAC \
  -macopt "hexkey:${KEY_HEX}" |
  awk '{print $NF}')

echo "${FIELDS}~hmac=${HMAC}"
```

{% hint style="info" %}
The PHP and Bash examples demonstrate the commonly used fields. If your implementation requires `st`, `id`, or `data`, include them in the specified signing order.
{% endhint %}

## HLS and DASH Streaming

For HLS and DASH streaming, use path mode with an ACL that covers the complete stream directory.

Example:

`/protected/movie/*`

This allows the manifest and its associated segments to use the same token.

When configuring token expiration:

* Set `exp` to cover the expected viewing session, including a reasonable buffer.
* Refresh tokens before expiration for long-running or live streams.
* Avoid IP-bound tokens for viewers who frequently switch between mobile and Wi-Fi networks.
* Generate tokens on your application server for each viewer session.

If a token expires while playback is in progress, subsequent segment requests return `403 Forbidden`.

## Caching Behavior

Auth Token 2.0 validation is performed at the Medianova edge before protected content is delivered.

The token is removed before cache lookup or origin forwarding.

As a result:

* The origin does not receive the token.
* Different valid tokens can access the same cached content.
* The token is not included in the cache key.
* Token validation also applies to cache hits.

This allows protected resources to benefit from CDN caching without bypassing token validation.

## Key Rotation

Auth Token 2.0 supports key rotation using two simultaneously active keys.

To rotate a key:

1. Contact Medianova Support to add the new shared key.
2. Update your application to generate tokens using the new key.
3. Allow previously generated tokens to expire.
4. Contact Medianova Support to retire the old key.

{% hint style="info" %}
If a shared key may have been exposed, contact [Medianova Support](https://clients.medianova.com/support-and-troubleshooting/contacting-customer-support.md) to arrange immediate rotation. Do not wait for the normal rotation schedule.
{% endhint %}

## Troubleshooting

Auth Token 2.0 rejects invalid requests with `403 Forbidden`.

The response does not disclose which validation check failed.

| Issue                                       | Possible cause                             | Recommended action                               |
| ------------------------------------------- | ------------------------------------------ | ------------------------------------------------ |
| All requests return 403                     | Incorrect signing order or key encoding    | Compare your signature against the test vector.  |
| Fresh tokens return 403                     | Incorrect server time                      | Synchronize your server clock using NTP.         |
| Manifest works but segments fail            | ACL does not cover segment paths           | Use a wildcard covering the stream directory.    |
| Only some viewers receive 403               | IP restriction does not match              | Review or remove the `ip` parameter.             |
| Token works in query mode but not path mode | Incorrect token placement mode             | Confirm the configured mode with Support.        |
| ACL does not match                          | URL encoding or path normalization differs | Verify the normalized request path.              |
| Playback stops during a session             | Token expired                              | Extend the validity period or refresh the token. |

## Security Best Practices

* Store shared keys only in trusted server-side environments.
* Generate tokens on your application server, never in client-side code.
* Use the shortest practical token expiration period.
* Limit token access to the required files or directories.
* Avoid overly broad ACL patterns such as `/*` unless necessary.
* Use the optional `id` field to associate tokens with viewer sessions for troubleshooting.
* Consider IP restrictions only when viewer IP addresses are expected to remain stable.
* Rotate keys if they may have been exposed.

{% hint style="info" %}
An Auth Token 2.0 is a bearer credential. Anyone who obtains a valid tokenized URL may use it until the token expires, unless additional restrictions such as IP binding apply.
{% endhint %}

## Need Help?

Contact [**Medianova Support**](https://clients.medianova.com/support-and-troubleshooting/contacting-customer-support.md) if you need to:

* Enable Auth Token 2.0 for your hostname.
* Configure protected paths.
* Obtain or rotate your shared secret key.
* Confirm the supported token placement mode.
* Investigate token validation failures.

When reporting a problem, include your CDN hostname and an example failing URL. Remove the HMAC signature and any sensitive information before sharing the URL.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://clients.medianova.com/products/security/auth-token-2-0.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
