Use estes exemplos em Python para implementar a assinatura de URL no lado do servidor para autenticação de URL do Alibaba Cloud CDN. Cada tipo de assinatura gera um formato diferente de URL assinada. Escolha o tipo correspondente à sua configuração de autenticação de URL do CDN.
Escolha um tipo de assinatura
|
Tipo de assinatura |
Formato da URL assinada |
Quando usar |
|
Tipo A |
|
Adiciona a chave de autenticação como parâmetro de consulta. Use quando suas URLs já tiverem strings de consulta. |
|
Tipo B |
|
Incorpora o timestamp e o hash no caminho. Use para manter a string de consulta limpa. |
|
Tipo C |
|
Insere o hash e a expiração hexadecimal no caminho. Use para autenticação compacta baseada em caminho. |
Para obter detalhes sobre o algoritmo de cada tipo de assinatura, consulte Type A signing, Type B signing e Type C signing.
Estes exemplos geram URLs assinadas no seu servidor de assinatura. Após gerar as URLs assinadas, configure a autenticação de URL no console do Alibaba Cloud CDN para validá-las. Consulte Próximos passos .
Parâmetros
|
Parâmetro |
Descrição |
Padrão |
Exemplo |
|
|
URL original a assinar |
— |
|
|
|
Chave privada configurada nas definições de autenticação de URL do CDN |
— |
|
|
|
Tempo de expiração como timestamp UNIX. Defina como a hora atual mais o TTL desejado. |
— |
|
|
|
String aleatória incluída na string assinada para assinatura Tipo A. |
|
|
|
|
Identificador de usuário incluído na string assinada para assinatura Tipo A. |
|
|
Observações de uso
Há exemplos para Python 2 e Python 3 porque o Python 3 não é retrocompatível com o Python 2.
O Python 2 usa codificação ASCII; o Python 3 usa UTF-8. Os exemplos em Python 3 passam
encoding='utf-8'parahashlib.md5()para garantir o cálculo correto do hash.Se uma URL contiver caracteres chineses, aplique a codificação de URL com
UrlEncode()antes de executar o código de assinatura.O TTL definido pelo servidor de assinatura e o TTL configurado no Alibaba Cloud CDN são independentes. O período de validade efetivo de uma URL assinada é: timestamp UNIX (servidor de assinatura) + TTL (servidor de assinatura) + TTL (Alibaba Cloud CDN). Exemplo: timestamp UNIX
1444435200+ TTL do servidor de assinatura3600+ TTL do CDN1800= validade termina em1444440600.
Assinatura Tipo A
A assinatura Tipo A adiciona auth_key como parâmetro de consulta. A string assinada é: <path>-<exp>-<rand>-<uid>-<key>.
Formato da URL assinada:
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()
Assinatura Tipo B
A assinatura Tipo B converte o tempo de expiração para o formato YYYYmmddHHMM usando strftime('%Y%m%d%H%M') e incorpora o timestamp e o hash no caminho da URL. A string assinada é: key + nexp + path.
Formato da URL assinada:
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()
Assinatura Tipo C
A assinatura Tipo C converte o tempo de expiração para hexadecimal usando "%x" % exp e insere o hash e a expiração hexadecimal no caminho da URL. A string assinada é: key + path + hexexp.
Formato da URL assinada:
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()
Próximos passos
Após gerar as URLs assinadas no servidor de assinatura, configure a autenticação de URL no console do Alibaba Cloud CDN para validá-las: