# Advanced hotlink protection for CDN

> Turn on advanced authentication on Bitiful CDN and generate signed links from a key and an expiration time, with multi-language code and troubleshooting.

> **Note**
>
> To prevent resource abuse, a CDN can use Referer and IP allowlists and blocklists to decide whether a request is legitimate. However, a Referer can be **forged easily**, so risks remain in practice.
>
> To better protect your origin resources, the CDN supports encrypting URLs with **advanced authentication (高级鉴权)**, responding correctly to legitimate requests and rejecting illegitimate ones.

## How it works

In the console, turn on **Advanced authentication (高级鉴权)** for the CDN domain you want to protect, and set a key (called the `authentication key` below, and **Key value (密钥值)** in the console). Your server uses the same algorithm and key to generate encrypted URLs for legitimate users, and sets the URL's expiration time with the `_ts` parameter.

When a user accesses a resource, the edge decides whether the request is legitimate by the following rules:

### Is there a signature?

- **Yes** - `Continue to the next rule`
- **No** - `Return 403 Forbidden`

### Has the current time not passed the timestamp given by the _ts parameter?

- **Yes** - `Continue to the next rule`
- **No** - `Return 403 Forbidden`

### Is _btf_tk valid? (This prevents _ts from being forged)

- **Yes** - `200 and return the resource`
- **No** - `Return 403 Forbidden`

## Turn it on in the console

1. Go to **CDN › Static Acceleration Management (静态加速管理)** ([open](https://console.bitiful.com/cdn/list)), click **Manage (管理)** for the domain, and switch to **Access Control (访问控制)**.
2. On the **Advanced authentication (高级鉴权)** card, click **Edit (编辑)** and set **Status (状态)** to **On (开启)**.
3. Fill in the **Key value (密钥值)**: letters and digits only, 8 to 30 characters long.
4. Click **Save (保存)**. It takes effect once the status goes from **Deploying (部署中)** back to **Running (运行中)**, usually within 30 seconds.

| Message                                                                        | What to do                               |
| ------------------------------------------------------------------------------ | ---------------------------------------- |
| **请输入鉴权密钥** (Enter the authentication key)                                     | A key is required when you turn it on.   |
| **鉴权密钥只能包含字母和数字** (The authentication key can contain only letters and digits) | Remove symbols, spaces, and line breaks. |
| **secretKey长度满足8～30个字符** (The secretKey must be 8 to 30 characters long)       | Adjust the key length.                   |

- Once turned on, every link on this CDN domain must be signed; there is no option to apply it per directory. Use a separate CDN domain for public resources.
- After you change the key, all links generated with the old key stop working.
- The console stores only one key; there is no backup key.
- `_btf_tk` and `_ts` are not part of the cache key, so links with different signatures share the same cache entry.

## Typical example

Taking the key `testsecretkey` as an example, a valid advanced hotlink protection URL looks like this:

> Regular URL: [http://tests3origin.dogecast.com/image.jpg?`_btf_tk`=2e1864801d8cb957a9e40b59ca4321d7&`_ts`=1701091625](http://tests3origin.dogecast.com/image.jpg?_btf_tk=2e1864801d8cb957a9e40b59ca4321d7&_ts=1701091625)
>
> URL with parameters: [http://tests3origin.dogecast.com/image.jpg?`_btf_tk`=93f766e73a684b47d2df17eae38d9849&`_ts`=1701091625&`fmt`=info](http://tests3origin.dogecast.com/image.jpg?_btf_tk=93f766e73a684b47d2df17eae38d9849&_ts=1701091625\&fmt=info)

Where:

- `_ts`: a Unix timestamp (in seconds) giving the URL's expiration time (the link returns 403 **after that time**). The time in the example expired long ago and is used only to verify signatures
- `_btf_tk` (regular URL): the MD5 of **tokenKey** + **path** (/image.jpg in this example) + **ts** (1701091625 in this example), as lowercase hexadecimal
- `_btf_tk` (URL with parameters): the MD5 of **tokenKey** + **path** (/image.jpg in this example) + **?** + **args** (\_ts=1701091625\&fmt=info in this example), as lowercase hexadecimal

> **Tip**
>
> Signing rules for URLs with parameters
>
> - In short: write the full path and parameters without `_btf_tk`, put **tokenKey** in front, compute the MD5, and then add `_btf_tk` to the URL;
> - **args** starts with `_ts=<timestamp>`, followed by the remaining parameters, joined with `&`;
> - The order and spelling of `_ts` and the remaining parameters in the URL must match exactly what you signed; `_btf_tk` can be placed at the beginning or the end;
> - All parameters are protected by the signature. Adding, removing, changing, or reordering them returns 403;
> - Parameter values must be URL-encoded first (for example `;`, `"`, spaces, and Chinese characters), and the signature and the URL must use **the same** encoded result;
> - **path** starts with `/` and uses the form that actually appears in the URL. If the path contains Chinese characters, spaces, and so on, sign with the encoded path.

> **Note**
>
> Some CDN domains created early on use a different route whose signing rule differs slightly: the remaining parameters aren't part of the signature, and a URL with parameters is signed the same way as a regular URL, that is, **tokenKey** + **path** + **ts**. If a URL with parameters returns 403 when signed with the rules above while the regular URL works, use this algorithm instead, or contact Bitiful to confirm.

## Verify the signature

The console does not currently have an authentication calculator. You can compute the signature of a **regular URL** and a **URL with parameters** with the commands below and compare it with your own code:

```bash
KEY="testsecretkey"      # Key value
URI_PATH="/image.jpg"    # Starts with /, the encoded path
TS=1701091625            # Expiration time

printf '%s%s%s' "$KEY" "$URI_PATH" "$TS" | openssl md5 | awk '{print $NF}'
# Outputs 2e1864801d8cb957a9e40b59ca4321d7
```

The signature of a **URL with parameters**:

```bash
ARGS="fmt=info"          # Remaining parameters, joined with &, values already encoded

printf '%s%s?_ts=%s&%s' "$KEY" "$URI_PATH" "$TS" "$ARGS" | openssl md5 | awk '{print $NF}'
# Outputs 93f766e73a684b47d2df17eae38d9849
```

## Code examples

Below is example code in several mainstream languages that generates the `advanced authentication URL` from the **typical example** above. Each example outputs both a **regular URL** and a **URL with parameters**, and can run in common online runtime environments.

> **Warning**
>
> **Security note:**
>
> Although some examples below are in client-side languages, always **generate advanced authentication links on the server only** and then distribute them to clients. This lets you:
>
> 1. Protect the **tokenKey** as much as possible;
> 2. Replace the **tokenKey** safely at any time without making users update their clients.

### PHP version

```php
<?php
function createLink($fileName, $params = []) {
    $deadLine = time() + 60; # The link is valid for the next 60 seconds
    $tokenKey = "testsecretkey"; # The authentication key set in the Bitiful console
    $domain = "http://tests3origin.dogecast.com";
    $query = "";
    foreach ($params as $k => $v) {
        $pair = $k . "=" . rawurlencode($v);
        $query .= "&" . $pair;   # The same string is used for signing and in the URL
    }
    $md5RawString = empty($params)
        ? $tokenKey . $fileName . $deadLine
        : $tokenKey . $fileName . "?_ts=" . $deadLine . $query;
    $md5Result = md5($md5RawString);
    return $domain . $fileName . "?_btf_tk=" . $md5Result . "&_ts=" . $deadLine . $query;
}

$path = "/image.jpg";
echo "Regular URL: ", createLink($path), "\n";
echo "URL with parameters: ", createLink($path, ["fmt" => "info"]), "\n";
```

### Go version

> **Tip**
>
> Validity of time.Now().Unix()
>
> - Most Go playgrounds cannot provide the real time, so `time.Now().Unix()` returns an incorrect, much earlier time;
> - Choose a third-party Go playground that supports it;
> - The Go example below runs correctly on [Programiz](https://www.programiz.com/golang/online-compiler/).

```go
package main

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"net/url"
	"strings"
	"time"
)

type Param struct{ Key, Value string }

func encode(v string) string {
	return strings.ReplaceAll(url.QueryEscape(v), "+", "%20")
}

func createLink(fileName string, params []Param) string {
	deadLine := time.Now().Unix() + 60 // The link is valid for the next 60 seconds
	tokenKey := "testsecretkey" // The authentication key set in the Bitiful console
	domain := "http://tests3origin.dogecast.com"
	query := ""
	for _, p := range params {
		pair := p.Key + "=" + encode(p.Value)
		query += "&" + pair // The same string is used for signing and in the URL
	}
	var rawString string
	if len(params) == 0 {
		rawString = fmt.Sprintf("%s%s%d", tokenKey, fileName, deadLine)
	} else {
		rawString = fmt.Sprintf("%s%s?_ts=%d%s", tokenKey, fileName, deadLine, query)
	}
	sum := md5.Sum([]byte(rawString))
	md5Result := hex.EncodeToString(sum[:])
	return fmt.Sprintf("%s%s?_btf_tk=%s&_ts=%d%s", domain, fileName, md5Result, deadLine, query)
}

func main() {
	path := "/image.jpg"
	fmt.Println("Regular URL: ", createLink(path, nil))
	fmt.Println("URL with parameters: ", createLink(path, []Param{{"fmt", "info"}}))
}
```

### Python3 version

```python
import hashlib
import time
from urllib.parse import quote

def create_link(fileName, params=None):
    params = params or {}
    deadLine = int(time.time()) + 60 # The link is valid for the next 60 seconds
    tokenKey = "testsecretkey" # The authentication key set in the Bitiful console
    domain = "http://tests3origin.dogecast.com"
    pairs = [f"{k}={quote(str(v), safe='')}" for k, v in params.items()]
    query = "".join("&" + p for p in pairs)  # The same string is used for signing and in the URL
    if pairs:
        rawString = f"{tokenKey}{fileName}?_ts={deadLine}{query}"
    else:
        rawString = f"{tokenKey}{fileName}{deadLine}"
    md5Result = hashlib.md5(rawString.encode()).hexdigest()
    return f"{domain}{fileName}?_btf_tk={md5Result}&_ts={deadLine}{query}"

path = "/image.jpg"
print("Regular URL: ", create_link(path))
print("URL with parameters: ", create_link(path, {"fmt": "info"}))
```

### JS version

```javascript
const crypto = require('crypto');

function createLink(fileName, params = {}) {
    let deadLine = Math.floor(Date.now() / 1000) + 60; // The link is valid for the next 60 seconds
    let tokenKey = "testsecretkey"; // The authentication key set in the Bitiful console
    let domain = "http://tests3origin.dogecast.com";
    let pairs = Object.entries(params).map(([k, v]) => `${k}=${encodeURIComponent(v)}`);
    let query = pairs.map(p => "&" + p).join("");  // The same string is used for signing and in the URL
    let rawString = pairs.length
        ? tokenKey + fileName + "?_ts=" + deadLine + query
        : tokenKey + fileName + deadLine;
    let md5Result = crypto.createHash('md5').update(rawString).digest('hex');
    return domain + fileName + "?_btf_tk=" + md5Result + "&_ts=" + deadLine + query;
}

const path = "/image.jpg";
console.log("Regular URL: ", createLink(path));
console.log("URL with parameters: ", createLink(path, { "fmt": "info" }));
```

### Java version

```java
import java.math.BigInteger;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String path = "/image.jpg";
        Map<String, String> params = new LinkedHashMap<>();
        params.put("fmt", "info");
        System.out.println("Regular URL: " + createLink(path, Collections.emptyMap()));
        System.out.println("URL with parameters: " + createLink(path, params));
    }

    public static String createLink(String fileName, Map<String, String> params) {
        long deadline = Instant.now().getEpochSecond() + 60; // The link is valid for the next 60 seconds
        String tokenKey = "testsecretkey"; // The authentication key set in the Bitiful console
        String domain = "http://tests3origin.dogecast.com";
        StringBuilder query = new StringBuilder();
        for (Map.Entry<String, String> e : params.entrySet()) {
            String pair = e.getKey() + "=" + encode(e.getValue());
            query.append("&").append(pair);  // The same string is used for signing and in the URL
        }
        String rawString = params.isEmpty()
            ? tokenKey + fileName + deadline
            : tokenKey + fileName + "?_ts=" + deadline + query;
        String md5Result = getMd5(rawString);
        return domain + fileName + "?_btf_tk=" + md5Result + "&_ts=" + deadline + query;
    }

    public static String encode(String v) {
        return URLEncoder.encode(v, StandardCharsets.UTF_8).replace("+", "%20");
    }

    public static String getMd5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes(StandardCharsets.UTF_8));
            BigInteger no = new BigInteger(1, messageDigest);
            String hashtext = no.toString(16);
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        }
        catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}
```

### Rust version

```rust
extern crate chrono;
extern crate crypto;

use chrono::prelude::*;
use crypto::digest::Digest;
use crypto::md5::Md5;
use urlencoding::encode;

fn create_link(file_name: &str, params: &[(&str, &str)]) -> String {
    let deadline = Utc::now().timestamp() + 60; // The link is valid for the next 60 seconds
    let token_key = "testsecretkey"; // The authentication key set in the Bitiful console
    let domain = "http://tests3origin.dogecast.com";
    let pairs: Vec<String> = params
        .iter()
        .map(|(k, v)| format!("{}={}", k, encode(v)))
        .collect();
    let query: String = pairs.iter().map(|p| format!("&{}", p)).collect(); // The same string is used for signing and in the URL
    let raw_string = if pairs.is_empty() {
        format!("{}{}{}", token_key, file_name, deadline)
    } else {
        format!("{}{}?_ts={}{}", token_key, file_name, deadline, query)
    };
    let mut hasher = Md5::new();
    hasher.input_str(&raw_string);
    let md5_result = hasher.result_str();
    format!("{}{}?_btf_tk={}&_ts={}{}", domain, file_name, md5_result, deadline, query)
}

fn main() {
    let path = "/image.jpg";
    println!("Regular URL: {}", create_link(path, &[]));
    println!("URL with parameters: {}", create_link(path, &[("fmt", "info")]));
}
```

**Note: before running the Rust code, add the following dependencies to your Cargo.toml file**

```toml
[dependencies]
chrono = "0.4"
rust-crypto = "0.2"
urlencoding = "2"
```

### Swift version

```swift
import CommonCrypto
import Foundation

func MD5(string: String) -> String {
    let length = Int(CC_MD5_DIGEST_LENGTH)
    var digest = [UInt8](repeating: 0, count: length)
    if let data = string.data(using: String.Encoding.utf8) {
        data.withUnsafeBytes { _ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest) }
    }
    return digest.map { String(format: "%02x", $0) }.joined()
}

func encode(_ v: String) -> String {
    let allowed = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~")
    return v.addingPercentEncoding(withAllowedCharacters: allowed) ?? v
}

func createLink(_ fileName: String, _ params: [(String, String)] = []) -> String {
    let deadline = Int(Date().timeIntervalSince1970) + 60
    let tokenKey = "testsecretkey"
    let domain = "http://tests3origin.dogecast.com"
    let pairs = params.map { "\($0.0)=\(encode($0.1))" }
    let query = pairs.map { "&\($0)" }.joined()  // The same string is used for signing and in the URL
    let rawString = pairs.isEmpty
        ? "\(tokenKey)\(fileName)\(deadline)"
        : "\(tokenKey)\(fileName)?_ts=\(deadline)\(query)"
    let md5Result = MD5(string: rawString)
    return "\(domain)\(fileName)?_btf_tk=\(md5Result)&_ts=\(deadline)\(query)"
}

let path = "/image.jpg"
print("Regular URL: ", createLink(path))
print("URL with parameters: ", createLink(path, [("fmt", "info")]))
```

### Kotlin version

```kotlin
import java.net.URLEncoder
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.time.Instant

fun encode(v: String): String = URLEncoder.encode(v, StandardCharsets.UTF_8).replace("+", "%20")

fun createLink(fileName: String, params: List<Pair<String, String>> = emptyList()): String {
    val deadline = Instant.now().epochSecond + 60
    val tokenKey = "testsecretkey"
    val domain = "http://tests3origin.dogecast.com"
    val pairs = params.map { (k, v) -> "$k=${encode(v)}" }
    val query = pairs.joinToString("") { "&$it" }  // The same string is used for signing and in the URL
    val rawString = if (pairs.isEmpty()) {
        "$tokenKey$fileName$deadline"
    } else {
        "$tokenKey$fileName?_ts=$deadline$query"
    }
    val md = MessageDigest.getInstance("MD5")
    md.update(rawString.toByteArray())
    val md5Result = md.digest().joinToString("") { "%02x".format(it) }
    return "$domain$fileName?_btf_tk=$md5Result&_ts=$deadline$query"
}

fun main() {
    val path = "/image.jpg"
    println("Regular URL: ${createLink(path)}")
    println("URL with parameters: ${createLink(path, listOf("fmt" to "info"))}")
}
```

## Troubleshoot a 403 response

1. Check whether the console status has returned to **Running** and whether the key matches the one in your code.
2. Check whether `_ts` is a timestamp in seconds, whether it has expired, and whether the server clock is accurate.
3. Check whether the signed path starts with `/` and matches the form in the URL (including encoding and case).
4. Test with a regular URL that has no other parameters first, then test the URL with parameters.
5. Check whether the request is being rejected by other rules, such as a [Referer, IP, or User-Agent list](https://docs.bitiful.com/en/cdn/handbook/access-control.md) you also set.
