閱讀840 返回首頁    go 財經資訊


鑒權代碼示例__周邊工具_CDN-阿裏雲

概述

URL鑒權規則請查閱 URL鑒權文檔,通過這個 demo 您可以根據業務需要,方便的對URL進行鑒權處理。以下Python Demo包含三種鑒權方式:A鑒權方式、B鑒權方式、C鑒權方式,分別描述了三種不同鑒權方式的請求URL構成、哈希字符串構成等內容

Python版本

  1. import re
  2. import time
  3. import hashlib
  4. import datetime
  5. def md5sum(src):
  6. m = hashlib.md5()
  7. m.update(src)
  8. return m.hexdigest()
  9. def a_auth(uri, key, exp):
  10. p = re.compile("^(https://|https://)?([^/?]+)(/[^?]*)?(\?.*)?$")
  11. if not p:
  12. return None
  13. m = p.match(uri)
  14. scheme, host, path, args = m.groups()
  15. if not scheme: scheme = "https://"
  16. if not path: path = "/"
  17. if not args: args = ""
  18. rand = "0" # "0" by default, other value is ok
  19. uid = "0" # "0" by default, other value is ok
  20. sstring = "%s-%s-%s-%s-%s" %(path, exp, rand, uid, key)
  21. hashvalue = md5sum(sstring)
  22. auth_key = "%s-%s-%s-%s" %(exp, rand, uid, hashvalue)
  23. if args:
  24. return "%s%s%s%s&auth_key=%s" %(scheme, host, path, args, auth_key)
  25. else:
  26. return "%s%s%s%s?auth_key=%s" %(scheme, host, path, args, auth_key)
  27. def b_auth(uri, key, exp):
  28. p = re.compile("^(https://|https://)?([^/?]+)(/[^?]*)?(\?.*)?$")
  29. if not p:
  30. return None
  31. m = p.match(uri)
  32. scheme, host, path, args = m.groups()
  33. if not scheme: scheme = "https://"
  34. if not path: path = "/"
  35. if not args: args = ""
  36. # convert unix timestamp to "YYmmDDHHMM" format
  37. nexp = datetime.datetime.fromtimestamp(exp).strftime('%Y%m%d%H%M')
  38. sstring = key + nexp + path
  39. hashvalue = md5sum(sstring)
  40. return "%s%s/%s/%s%s%s" %(scheme, host, nexp, hashvalue, path, args)
  41. def c_auth(uri, key, exp):
  42. p = re.compile("^(https://|https://)?([^/?]+)(/[^?]*)?(\?.*)?$")
  43. if not p:
  44. return None
  45. m = p.match(uri)
  46. scheme, host, path, args = m.groups()
  47. if not scheme: scheme = "https://"
  48. if not path: path = "/"
  49. if not args: args = ""
  50. hexexp = "%x" %exp
  51. sstring = key + path + hexexp
  52. hashvalue = md5sum(sstring)
  53. return "%s%s/%s/%s%s%s" %(scheme, host, hashvalue, hexexp, path, args)
  54. def main():
  55. uri = "https://xc.cdnpe.com/ping?foo=bar" # original uri
  56. key = "<input private key>" # private key of authorization
  57. exp = int(time.time()) + 1 * 3600 # expiration time: 1 hour after current itme
  58. authuri = a_auth(uri, key, exp) # auth type: a_auth / b_auth / c_auth
  59. print("URL : %snAUTH: %s" %(uri, authuri))
  60. if __name__ == "__main__":
  61. main()

最後更新:2016-12-19 10:00:09

  上一篇:go 日誌合並工具__周邊工具_CDN-阿裏雲
  下一篇:go CDN服務如何開啟GZIP壓縮功能___產品使用問題_CDN-阿裏雲