全部產品
Search
文件中心

CDN:鑒權程式碼範例

更新時間:Jun 30, 2024

本文以Python Demo為您樣本,介紹三種鑒權方式的實現方法。

程式碼範例

程式碼範例如下所示。

說明
  • Python有Python2和Python3兩個主要的版本,由於Python3不完全向下相容Python2,因此下面分別給出了Python2和Python3的程式碼範例。

  • 如果URL中包含中文字元,請先對URL中的中文字元進行UrlEncode編碼,然後再運行代碼實現鑒權處理。

  • 由於Python2使用的是ASCII編碼,而Python3使用的是UTF-8編碼,hash傳遞時需要使用UTF-8類型,因此,Python3程式碼範例的md5 hash環節增加了編碼轉換處理。

Python3

import re
import time
import hashlib
import datetime
def md5sum(src):
    m = hashlib.md5()
    m.update(src.encode(encoding='utf-8'))                                    #增加了編碼方式轉換處理
    return m.hexdigest()
    #鑒權方式A
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)
    #鑒權方式B
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 = ""
    # convert unix timestamp to "YYmmDDHHMM" format
    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)
    #鑒權方式C
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)
    #以下內容為uri、key、exp這三個參數的取值代碼
def main():
    uri = "http://example.aliyundoc.com/ping?foo=bar"            # original uri
    key = "<input private key>"                         # private key of authorization
    exp = int(time.time()) + 1 * 3600                   # expiration time: 1 hour after current time
    #“1 * 3600”定義了簽算伺服器配置的鑒權URL的有效時間長度,使用者可以任意配置,單位是秒。簽算伺服器配置的鑒權URL有效時間長度和CDN配置的鑒權URL有效時間長度沒有對應關係。
    #鑒權URL的實際到期時間=簽算伺服器的Unix時間戳記+簽算伺服器配置的鑒權URL有效時間長度+CDN配置的鑒權URL有效時間長度
    #以調用鑒權方式A為例,簽算伺服器的Unix時間戳記=1444435200,簽算伺服器配置的鑒權URL有效時間長度=3600,CDN配置的鑒權URL有效時間長度=1800,則鑒權URL的實際到期時間為1444435200+3600+1800=1444440600
    #以下內容是調用A鑒權演算法的程式碼範例:
    authuri = a_auth(uri, key, exp)                     # auth type: a_auth / b_auth / c_auth
    print("URL : %s\nAUTH: %s" %(uri, authuri))
if __name__ == "__main__":
    main()

Python2

import re
import time
import hashlib
import datetime
def md5sum(src):
    m = hashlib.md5()
    m.update(src)
    return m.hexdigest()
    #鑒權方式A
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)
    #鑒權方式B
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 = ""
    # convert unix timestamp to "YYmmDDHHMM" format
    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)
    #鑒權方式C
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)
    #以下內容為uri、key、exp這三個參數的取值代碼
def main():
    uri = "http://example.aliyundoc.com/ping?foo=bar"            # original uri
    key = "<input private key>"                         # private key of authorization
    exp = int(time.time()) + 1 * 3600                   # expiration time: 1 hour after current time
    #“1 * 3600”定義了簽算伺服器配置的鑒權URL的有效時間長度,使用者可以任意配置,單位是秒。簽算伺服器配置的鑒權URL有效時間長度和CDN配置的鑒權URL有效時間長度沒有對應關係。
    #鑒權URL的實際到期時間=簽算伺服器的Unix時間戳記+簽算伺服器配置的鑒權URL有效時間長度+CDN配置的鑒權URL有效時間長度
    #以調用鑒權方式A為例,簽算伺服器的Unix時間戳記=1444435200,簽算伺服器配置的鑒權URL有效時間長度=3600,CDN配置的鑒權URL有效時間長度=1800,則鑒權URL的實際到期時間為1444435200+3600+1800=1444440600
    #以下內容是調用A鑒權演算法的程式碼範例:
    authuri = a_auth(uri, key, exp)                     # auth type: a_auth / b_auth / c_auth
    print("URL : %s\nAUTH: %s" %(uri, authuri))
if __name__ == "__main__":
    main()