> 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/security-token/secure-token-v2-country-lock.md). Agents can also search and read this documentation through its [MCP server](https://clients.medianova.com/~gitbook/mcp).

# Secure Token v2 – Country Lock

Learn how to configure Secure Token v2 – Country Lock and generate signed URLs restricted to a specific country.

Secure Token v2 – Country Lock protects CDN content using signed, time-limited URLs associated with a country.

Medianova CDN identifies the viewer's country from their IP address. It validates the URL signature using that country code and the configured Token Key.

A signed URL works only when the detected country matches the country used to generate the signature.

## How Secure Token v2 – Country Lock works

Secure Token v2 – Country Lock generates an MD5 signature using the expiration timestamp, Token Key, and a two-letter country code.

When **Token URI** is enabled, the signature also includes the requested file's directory.

The validation process follows these stages:

1. **Token generation:** Your application signs the expiration time, secret key, country code, and optional directory.
2. **Content request:** The viewer requests a URL containing `st` and `e`.
3. **Country detection:** Medianova CDN identifies the viewer's country using its GeoIP database.
4. **Token validation:** The CDN calculates the expected signature using the detected country.
5. **Request handling:** The CDN processes valid requests and rejects requests that fail validation.

<figure><img src="https://542970813-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FtK7oIwmhUHdEJcaH4Hx8%2Fuploads%2FW9rDPZPsz1PDy2x1L6Xp%2Fimage.png?alt=media&amp;token=4af6d696-8c43-482d-a3ae-faa17a0f8e7b" alt=""><figcaption><p>Secure Token v2 – Country Lock</p></figcaption></figure>

The country code is part of the signature. It does not appear as a separate URL parameter.

{% hint style="info" %}
Country Lock restricts access by country, not by individual viewer. Multiple viewers in the same country can use the same valid signed URL.
{% endhint %}

### Understand Token URI behavior

<table><thead><tr><th width="109.5">Token URI</th><th>Signed values</th><th>Access scope</th></tr></thead><tbody><tr><td>Enabled</td><td>Expiration, Token Key, country code, directory</td><td>Files in the signed directory, from the specified country</td></tr><tr><td>Disabled</td><td>Expiration, Token Key, country code</td><td>All paths within the CDN Resource, from the specified country</td></tr></tbody></table>

{% hint style="warning" %}
Disabling Token URI removes directory restrictions. A valid token can authorize any path within the CDN Resource from the specified country until expiration.
{% endhint %}

## Supported CDN Resource types

Secure Token v2 – Country Lock is available for the following CDN Resource types:

| CDN Resource type | Availability  |
| ----------------- | ------------- |
| Small CDN         | Supported     |
| Large CDN         | Supported     |
| Large Streaming   | Supported     |
| Streaming         | Not supported |
| VOD               | Not supported |
| Dynamic CDN       | Not supported |

## Configure Secure Token v2 – Country Lock

Use the [Medianova Control Panel](https://cloud.medianova.com) to configure Secure Token v2 – Country Lock.

{% stepper %}
{% step %}

### Select a CDN Resource

Open the CDN Resource you want to protect in the [Medianova Control Panel](https://cloud.medianova.com).
{% endstep %}

{% step %}

### Open Security settings

Navigate to **Security → General**.
{% endstep %}

{% step %}

### Enable Security Token

Enable **Security Token**.
{% endstep %}

{% step %}

### Select Secure Token v2 – Country Lock

Choose **Secure Token v2 – Country Lock** from **Token Type**.

<figure><img src="https://542970813-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FtK7oIwmhUHdEJcaH4Hx8%2Fuploads%2FCeIdbnkHNr2C5ifDtxkJ%2Fimage.png?alt=media&amp;token=d762509e-fc79-4366-8d18-e08dce81ced7" alt=""><figcaption></figcaption></figure>
{% endstep %}

{% step %}

### Configure the Token Key

Enter your secret key in **Token Key**.

Store the same key securely in your application backend.
{% endstep %}

{% step %}

### Configure Token URI

Enable **Token URI** for directory-based signing.

Disable it only when the token must authorize all paths within the CDN Resource.
{% endstep %}

{% step %}

### Save the configuration

Click **Save** to apply your settings.
{% endstep %}
{% endstepper %}

{% hint style="warning" %}
Keep your Token Key confidential. Changing the key invalidates URLs generated with the previous key.
{% endhint %}

## Generate a signed URL

Secure Token v2 – Country Lock uses two required query parameters.

<table><thead><tr><th width="277.5">Parameter</th><th>Description</th></tr></thead><tbody><tr><td><code>st</code></td><td>MD5 signature encoded using Base64URL without padding.</td></tr><tr><td><code>e</code></td><td>Expiration time as a Unix timestamp in seconds.</td></tr></tbody></table>

Use an uppercase, two-letter ISO 3166-1 alpha-2 country code.

Examples include `TR` for Türkiye and `DE` for Germany.

The country code must match the country that Medianova CDN detects for the viewer.

### Generate a directory-based signature

When Token URI is enabled, include the directory path in the signature.

Use this formula:

```
st = base64url(MD5(e + " " + KEY + " " + COUNTRY + " " + DIRECTORY))
```

Where:

* `e` is the expiration timestamp.
* `KEY` is the configured Token Key.
* `COUNTRY` is the uppercase country code.
* `DIRECTORY` is the requested file's directory path.

Use exactly one space between each value.

**Verify the directory-based example**

Use the following values to test your implementation:

| Input           | Value                   |
| --------------- | ----------------------- |
| Token Key       | `ExampleKey2026`        |
| File path       | `/videos/sample.mp4`    |
| Directory       | `/videos/`              |
| Country         | `TR`                    |
| Expiration      | `1798761600`            |
| Expiration date | 2027-01-01 00:00:00 UTC |

The signed string is:

```
1798761600 ExampleKey2026 TR /videos/
```

The expected signature is:

```
SEG5vdYy5a_OcT5o3zzZ7Q
```

The resulting URL is:

```
https://cdn.example.com/videos/sample.mp4?st=SEG5vdYy5a_OcT5o3zzZ7Q&e=1798761600
```

The same token can authorize other files in `/videos/` when requests originate from a country detected as `TR`.

A request from a different country fails token validation.

### Generate a path-independent signature

When Token URI is disabled, exclude the directory path from the signature.

Use this formula:

```
st = base64url(MD5(e + " " + KEY + " " + COUNTRY))
```

Use exactly one space between the values.

**Verify the path-independent example**

Use the following values:

| Input           | Value                   |
| --------------- | ----------------------- |
| Token Key       | `ExampleKey2026`        |
| Country         | `TR`                    |
| Expiration      | `1798761600`            |
| Expiration date | 2027-01-01 00:00:00 UTC |

The signed string is:

```
1798761600 ExampleKey2026 TR
```

The expected signature is:

```
jkKF3A0BUMq0cMMPtGKVBg
```

The resulting URL is:

```
https://cdn.example.com/videos/sample.mp4?st=jkKF3A0BUMq0cMMPtGKVBg&e=1798761600
```

This token can authorize other paths within the CDN Resource when requests originate from the specified country.

{% hint style="warning" %}
The example key is for testing only. Never use example credentials in production.
{% endhint %}

## Generate signed URLs with Python

The following example supports both Token URI modes.

It reads the Token Key from an environment variable and generates a URL valid for one hour.

```python
import base64
import hashlib
import os
import time


def sign_url(
    base_url: str,
    path: str,
    key: str,
    ttl: int,
    country: str,
    token_uri: bool = True,
) -> str:
    expiration = int(time.time()) + ttl

    country = country.upper()

    if len(country) != 2 or not country.isalpha():
        raise ValueError("Use a two-letter country code.")

    signed_data = f"{expiration} {key} {country}"

    if token_uri:
        directory = path[:path.rfind("/") + 1]
        signed_data += f" {directory}"

    digest = hashlib.md5(signed_data.encode()).digest()

    signature = (
        base64.urlsafe_b64encode(digest)
        .rstrip(b"=")
        .decode()
    )

    return (
        f"{base_url}{path}"
        f"?st={signature}&e={expiration}"
    )


url = sign_url(
    base_url="https://cdn.example.com",
    path="/videos/sample.mp4",
    key=os.environ["MN_TOKEN_KEY"],
    ttl=3600,
    country="TR",
    token_uri=True,
)

print(url)
```

Set `MN_TOKEN_KEY` to the Token Key configured in the Medianova Control Panel.

Replace the example hostname and file path with your actual values.

Set `country` to the country you want to authorize.

Set `token_uri` to match the Token URI setting in the Control Panel.

The signature uses the raw 16-byte MD5 digest encoded with Base64URL. Remove trailing `=` padding characters.

{% hint style="warning" %}
Generate signed URLs on a trusted backend. Never expose the Token Key in client-side code or public repositories.
{% endhint %}

## Follow country and directory rules

### Match the viewer's country

Use an uppercase, two-letter ISO 3166-1 alpha-2 country code.

Medianova CDN detects the viewer's country using an IP-based GeoIP database.

The signed country must match the country detected by the CDN.

| Rule                            | Example                                            |
| ------------------------------- | -------------------------------------------------- |
| Use two-letter country codes.   | `TR`, `DE`, `US`                                   |
| Use uppercase letters.          | `TR`, not `tr`                                     |
| Sign one country per token.     | A token for `TR` does not authorize `DE`.          |
| Use the CDN's detected country. | The application and CDN must agree on the country. |

{% hint style="info" %}
GeoIP databases may classify some IP addresses differently. Mobile networks, proxies, and VPNs can affect the detected country.
{% endhint %}

Country Lock does not prevent access through a VPN whose exit IP address belongs to the authorized country.

### Match the signed directory

When Token URI is enabled, the signed directory must match the requested file's directory.

<table><thead><tr><th width="351">Rule</th><th>Example</th></tr></thead><tbody><tr><td>Begin the directory with <code>/</code>.</td><td><code>/videos/</code></td></tr><tr><td>Include the trailing <code>/</code>.</td><td><code>/videos/</code>, not <code>/videos</code></td></tr><tr><td>Exclude the hostname.</td><td>Sign <code>/videos/</code>, not the full URL.</td></tr><tr><td>Exclude query parameters.</td><td>Sign <code>/videos/</code> for <code>/videos/file.mp4?quality=hd</code>.</td></tr><tr><td>Preserve letter case.</td><td><code>/Videos/</code> differs from <code>/videos/</code>.</td></tr><tr><td>Use the normalized path.</td><td>Match the path expected by the CDN.</td></tr></tbody></table>

A token generated for `/videos/` does not authorize files in `/videos/series/`.

For the validated Small CDN implementation, unrelated query parameters are not included in the signature.

## Manage token expiration

The `e` parameter defines the expiration time as a Unix timestamp in seconds.

Calculate the expiration using the current Unix time and the required validity period.

For example, a one-hour token uses:

```
EXPIRATION = CURRENT_UNIX_TIME + 3600
```

Use a synchronized system clock when generating signatures.

After expiration, the CDN rejects new requests using the expired token.

A request that begins before expiration can complete. However, new requests require valid tokens.

{% hint style="info" %}
Use UTC-based Unix timestamps for signing. The source guide recommends UTC for the Token Timezone setting.
{% endhint %}

## Deploy Secure Token v2 – Country Lock safely

Prepare your application before enabling token enforcement.

{% stepper %}
{% step %}

### Generate a Token Key

Create a secure key for your application and CDN Resource.
{% endstep %}

{% step %}

### Implement URL signing

Add country-based signature generation to your application backend.
{% endstep %}

{% step %}

### Validate the signing implementation

Compare the generated signatures with the worked examples on this page.
{% endstep %}

{% step %}

### Deploy signed URLs

Update your application to distribute signed URLs for the required countries.
{% endstep %}

{% step %}

### Configure public path exceptions

Create the required Page Rules for content that must remain publicly accessible.
{% endstep %}

{% step %}

### Enable Secure Token v2 – Country Lock

Apply the prepared configuration in the Medianova Control Panel.
{% endstep %}

{% step %}

### Verify protected requests

Test valid, invalid, expired, and country-mismatched URLs.
{% endstep %}
{% endstepper %}

{% hint style="warning" %}
Enabling Security Token can cause existing unsigned URLs to fail. Deploy signed URL generation before enforcing validation.
{% endhint %}

## Validate Secure Token v2 – Country Lock requests

For the validated Small CDN implementation:

| Condition                                | HTTP response                        |
| ---------------------------------------- | ------------------------------------ |
| Valid signature, expiration, and country | Request proceeds to content delivery |
| Missing token                            | 403 Forbidden                        |
| Invalid signature                        | 403 Forbidden                        |
| Country mismatch                         | 403 Forbidden                        |
| Expired token                            | 410 Gone                             |

A successful token validation does not guarantee an HTTP 200 response. Content availability and other CDN settings still affect the final response.

## Troubleshoot Secure Token v2 – Country Lock

### HTTP 403 Forbidden

The CDN rejects requests that fail token validation.

Check the following:

* The URL contains both `st` and `e`.
* The application uses the correct Token Key.
* The country code contains two uppercase letters.
* The signed country matches the CDN's detected country.
* The signed values use exactly one space as a separator.
* The Token URI setting matches the signing method.
* The signed directory matches the requested path.
* The signature uses the raw MD5 digest.
* Base64URL encoding excludes `=` padding.

Compare your generated signature with the worked examples:

| Token URI | Expected signature       |
| --------- | ------------------------ |
| Enabled   | `SEG5vdYy5a_OcT5o3zzZ7Q` |
| Disabled  | `jkKF3A0BUMq0cMMPtGKVBg` |

### HTTP 410 Gone

For the validated Small CDN implementation, HTTP 410 indicates an expired token.

Generate a new signed URL with a future expiration timestamp.

Verify that the application clock is synchronized.

### A URL fails for a viewer in the expected country

The CDN may detect a different country for the viewer's IP address.

Check whether the viewer uses a VPN, proxy, or mobile network.

Verify the country classification used by Medianova CDN.

### A URL works through a VPN

Country Lock checks the country associated with the request IP address.

A VPN exit IP address in the authorized country can satisfy this restriction.

Use a different token type if country-based access control does not meet your security requirements.

### A token works for unexpected paths

Check the Token URI setting.

When Token URI is disabled, the signature does not include a directory path.

Enable Token URI when access must remain restricted to a specific directory.

### Signed URLs stop working after a key change

Changing the Token Key invalidates URLs generated with the previous key.

Update the signing key in your application and generate new URLs.

## Security recommendations

* Store the Token Key in a secure backend environment.
* Use uppercase ISO 3166-1 alpha-2 country codes.
* Account for differences between GeoIP databases.
* Use Token URI when directory-level restrictions are required.
* Avoid path-independent signing unless the use case requires it.
* Select expiration periods appropriate for the content.
* Use HTTPS when delivering protected content.
* Test country-mismatched requests before enabling enforcement.

{% hint style="warning" %}
Country Lock is not a substitute for identity-based authentication. Any viewer detected in the authorized country can use a valid shared URL.
{% endhint %}

## Related token types

For different access requirements, consider:

* [**Secure Token v2**](https://clients.medianova.com/products/security/security-token/secure-token-v2.md)**:** Protect directories without country restrictions.
* [**Secure Token v2 – IP Lock**](https://clients.medianova.com/products/security/security-token/secure-token-v2-ip-lock.md)**:** Bind signed access to a specific client IP address.
* [**Secure Token – IP & Cookie Lock**](https://clients.medianova.com/products/security/security-token/secure-token-ip-and-cookie-lock.md)**:** Bind access to an IP address and configured cookie values.

{% hint style="info" %}
For general feature configuration, refer to the [Security Token](https://clients.medianova.com/products/security/security-token.md) page.
{% endhint %}


---

# 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/security-token/secure-token-v2-country-lock.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.
