阅读840 返回首页    go 小米 go 小米5


鉴权代码示例__周边工具_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-阿里云