Tous les produits
Search
Centre de documentation

CDN:Exemples de signature d'URL

Dernière mise à jour :Aug 20, 2026

Utilisez ces exemples Python pour implémenter la signature d'URL côté serveur pour l'authentification des URL Alibaba Cloud CDN. Chaque type de signature génère un format d'URL signé différent : choisissez celui qui correspond à votre configuration d'authentification des URL CDN.

Choisir un type de signature

Type de signature Format de l'URL signée Cas d'utilisation
Type A http://example.com/path?auth_key=<exp>-<rand>-<uid>-<hash> Ajoute la clé d'authentification en tant que paramètre de requête. Utilisez cette méthode lorsque vos URL contiennent déjà des chaînes de requête.
Type B http://example.com/<YYYYmmddHHMM>/<hash>/path Intègre l'horodatage et le hachage dans le chemin. Privilégiez cette option si vous souhaitez conserver une chaîne de requête vide.
Type C http://example.com/<hash>/<hexexp>/path Intègre le hachage et l'expiration hexadécimale dans le chemin. Adapté aux scénarios d'authentification compacts basés sur le chemin.

Pour obtenir les détails algorithmiques de chaque type de signature, consultez les rubriques Signature de type A, Signature de type B et Signature de type C.

Ces exemples génèrent des URL signées sur votre serveur de signature. Après avoir généré les URL signées, configurez l'authentification des URL dans la console Alibaba Cloud CDN pour les valider. Consultez la section Étapes suivantes .

Paramètres

Paramètre Description Valeur par défaut Exemple
uri L'URL d'origine à signer — http://example.aliyundoc.com/ping?foo=bar
key La clé privée configurée dans vos paramètres d'authentification des URL CDN — <your-private-key>
exp L'heure d'expiration sous forme d'horodatage UNIX. Définissez-la sur l'heure actuelle plus la durée de vie (TTL) souhaitée. — int(time.time()) + 1 * 3600
rand Une chaîne aléatoire incluse dans la chaîne signée pour la signature de type A. "0" "0"
uid Un identifiant utilisateur inclus dans la chaîne signée pour la signature de type A. "0" "0"

Notes d'utilisation

  • Des exemples pour Python 2 et Python 3 sont fournis, car Python 3 n'est pas rétrocompatible avec Python 2.

  • Python 2 utilise l'encodage ASCII. Python 3 utilise l'encodage UTF-8. Les exemples Python 3 transmettent encoding='utf-8' à hashlib.md5() pour garantir un calcul correct du hachage.

  • Si une URL contient des caractères chinois, appliquez l'encodage d'URL avec UrlEncode() avant d'exécuter le code de signature.

  • La durée de vie (TTL) définie par votre serveur de signature et celle définie par Alibaba Cloud CDN sont indépendantes. La période de validité effective d'une URL signée est : Horodatage UNIX (serveur de signature) + TTL (serveur de signature) + TTL (Alibaba Cloud CDN). Exemple : horodatage UNIX 1444435200 + TTL du serveur de signature 3600 + TTL CDN 1800 = fin de la période de validité à 1444440600.

Signature de type A

La signature de type A ajoute auth_key en tant que paramètre de requête. La chaîne signée est : <path>-<exp>-<rand>-<uid>-<key>.

Format de l'URL signée :

http://example.aliyundoc.com/ping?foo=bar&auth_key=<exp>-<rand>-<uid>-<hash>

Python 3

import re
import time
import hashlib
import datetime

def md5sum(src):
    m = hashlib.md5()
    m.update(src.encode(encoding='utf-8'))  # UTF-8 encoding required for Python 3
    return m.hexdigest()

def a_auth(uri, key, exp):
    p = re.compile("^(http://|https://)?([^/?]+)(/[^?]*)?(\\?.*)?$")
    if not p:
        return None
    m = p.match(uri)
    scheme, host, path, args = m.groups()
    if not scheme: scheme = "http://"
    if not path: path = "/"
    if not args: args = ""
    rand = "0"      # "0" by default, other value is ok
    uid = "0"       # "0" by default, other value is ok
    sstring = "%s-%s-%s-%s-%s" %(path, exp, rand, uid, key)
    hashvalue = md5sum(sstring)
    auth_key = "%s-%s-%s-%s" %(exp, rand, uid, hashvalue)
    if args:
        return "%s%s%s%s&auth_key=%s" %(scheme, host, path, args, auth_key)
    else:
        return "%s%s%s%s?auth_key=%s" %(scheme, host, path, args, auth_key)

def main():
    uri = "http://example.aliyundoc.com/ping?foo=bar"   # original URI
    key = "<input private key>"                          # private key for URL authentication
    exp = int(time.time()) + 1 * 3600                   # expiration time: 1 hour after current time
    # "1 * 3600" is the TTL assigned by the signing server. Adjust based on your requirements. Unit: seconds.
    # The signing server TTL is independent of the Alibaba Cloud CDN TTL.
    # Validity period = UNIX timestamp (signing server) + TTL (signing server) + TTL (Alibaba Cloud CDN).
    # Example: timestamp 1444435200 + signing server TTL 3600 + CDN TTL 1800 = 1444440600.
    authuri = a_auth(uri, key, exp)
    print("URL : %s\nAUTH: %s" %(uri, authuri))

if __name__ == "__main__":
    main()

Python 2

import re
import time
import hashlib
import datetime

def md5sum(src):
    m = hashlib.md5()
    m.update(src)
    return m.hexdigest()

def a_auth(uri, key, exp):
    p = re.compile("^(http://|https://)?([^/?]+)(/[^?]*)?(\\?.*)?$")
    if not p:
        return None
    m = p.match(uri)
    scheme, host, path, args = m.groups()
    if not scheme: scheme = "http://"
    if not path: path = "/"
    if not args: args = ""
    rand = "0"      # "0" by default, other value is ok
    uid = "0"       # "0" by default, other value is ok
    sstring = "%s-%s-%s-%s-%s" %(path, exp, rand, uid, key)
    hashvalue = md5sum(sstring)
    auth_key = "%s-%s-%s-%s" %(exp, rand, uid, hashvalue)
    if args:
        return "%s%s%s%s&auth_key=%s" %(scheme, host, path, args, auth_key)
    else:
        return "%s%s%s%s?auth_key=%s" %(scheme, host, path, args, auth_key)

def main():
    uri = "http://example.aliyundoc.com/ping?foo=bar"   # original URI
    key = "<input private key>"                          # private key for URL authentication
    exp = int(time.time()) + 1 * 3600                   # expiration time: 1 hour after current time
    authuri = a_auth(uri, key, exp)
    print("URL : %s\nAUTH: %s" %(uri, authuri))

if __name__ == "__main__":
    main()

Signature de type B

La signature de type B convertit l'heure d'expiration au format YYYYmmddHHMM à l'aide de strftime('%Y%m%d%H%M'), puis intègre l'horodatage et le hachage dans le chemin de l'URL. La chaîne signée est : key + nexp + path.

Format de l'URL signée :

http://example.aliyundoc.com/<YYYYmmddHHMM>/<hash>/ping?foo=bar

Python 3

import re
import time
import hashlib
import datetime

def md5sum(src):
    m = hashlib.md5()
    m.update(src.encode(encoding='utf-8'))  # UTF-8 encoding required for Python 3
    return m.hexdigest()

def b_auth(uri, key, exp):
    p = re.compile("^(http://|https://)?([^/?]+)(/[^?]*)?(\\?.*)?$")
    if not p:
        return None
    m = p.match(uri)
    scheme, host, path, args = m.groups()
    if not scheme: scheme = "http://"
    if not path: path = "/"
    if not args: args = ""
    nexp = datetime.datetime.fromtimestamp(exp).strftime('%Y%m%d%H%M')
    sstring = key + nexp + path
    hashvalue = md5sum(sstring)
    return "%s%s/%s/%s%s%s" %(scheme, host, nexp, hashvalue, path, args)

def main():
    uri = "http://example.aliyundoc.com/ping?foo=bar"   # original URI
    key = "<input private key>"                          # private key for URL authentication
    exp = int(time.time()) + 1 * 3600                   # expiration time: 1 hour after current time
    authuri = b_auth(uri, key, exp)
    print("URL : %s\nAUTH: %s" %(uri, authuri))

if __name__ == "__main__":
    main()

Python 2

import re
import time
import hashlib
import datetime

def md5sum(src):
    m = hashlib.md5()
    m.update(src)
    return m.hexdigest()

def b_auth(uri, key, exp):
    p = re.compile("^(http://|https://)?([^/?]+)(/[^?]*)?(\\?.*)?$")
    if not p:
        return None
    m = p.match(uri)
    scheme, host, path, args = m.groups()
    if not scheme: scheme = "http://"
    if not path: path = "/"
    if not args: args = ""
    nexp = datetime.datetime.fromtimestamp(exp).strftime('%Y%m%d%H%M')
    sstring = key + nexp + path
    hashvalue = md5sum(sstring)
    return "%s%s/%s/%s%s%s" %(scheme, host, nexp, hashvalue, path, args)

def main():
    uri = "http://example.aliyundoc.com/ping?foo=bar"   # original URI
    key = "<input private key>"                          # private key for URL authentication
    exp = int(time.time()) + 1 * 3600                   # expiration time: 1 hour after current time
    authuri = b_auth(uri, key, exp)
    print("URL : %s\nAUTH: %s" %(uri, authuri))

if __name__ == "__main__":
    main()

Signature de type C

La signature de type C convertit l'heure d'expiration en hexadécimal à l'aide de "%x" % exp, puis intègre le hachage et l'expiration hexadécimale dans le chemin de l'URL. La chaîne signée est : key + path + hexexp.

Format de l'URL signée :

http://example.aliyundoc.com/<hash>/<hexexp>/ping?foo=bar

Python 3

import re
import time
import hashlib
import datetime

def md5sum(src):
    m = hashlib.md5()
    m.update(src.encode(encoding='utf-8'))  # UTF-8 encoding required for Python 3
    return m.hexdigest()

def c_auth(uri, key, exp):
    p = re.compile("^(http://|https://)?([^/?]+)(/[^?]*)?(\\?.*)?$")
    if not p:
        return None
    m = p.match(uri)
    scheme, host, path, args = m.groups()
    if not scheme: scheme = "http://"
    if not path: path = "/"
    if not args: args = ""
    hexexp = "%x" %exp
    sstring = key + path + hexexp
    hashvalue = md5sum(sstring)
    return "%s%s/%s/%s%s%s" %(scheme, host, hashvalue, hexexp, path, args)

def main():
    uri = "http://example.aliyundoc.com/ping?foo=bar"   # original URI
    key = "<input private key>"                          # private key for URL authentication
    exp = int(time.time()) + 1 * 3600                   # expiration time: 1 hour after current time
    authuri = c_auth(uri, key, exp)
    print("URL : %s\nAUTH: %s" %(uri, authuri))

if __name__ == "__main__":
    main()

Python 2

import re
import time
import hashlib
import datetime

def md5sum(src):
    m = hashlib.md5()
    m.update(src)
    return m.hexdigest()

def c_auth(uri, key, exp):
    p = re.compile("^(http://|https://)?([^/?]+)(/[^?]*)?(\\?.*)?$")
    if not p:
        return None
    m = p.match(uri)
    scheme, host, path, args = m.groups()
    if not scheme: scheme = "http://"
    if not path: path = "/"
    if not args: args = ""
    hexexp = "%x" %exp
    sstring = key + path + hexexp
    hashvalue = md5sum(sstring)
    return "%s%s/%s/%s%s%s" %(scheme, host, hashvalue, hexexp, path, args)

def main():
    uri = "http://example.aliyundoc.com/ping?foo=bar"   # original URI
    key = "<input private key>"                          # private key for URL authentication
    exp = int(time.time()) + 1 * 3600                   # expiration time: 1 hour after current time
    authuri = c_auth(uri, key, exp)
    print("URL : %s\nAUTH: %s" %(uri, authuri))

if __name__ == "__main__":
    main()

Étapes suivantes

Après avoir généré des URL signées sur votre serveur de signature, configurez l'authentification des URL dans la console Alibaba Cloud CDN pour les valider :