全部产品
弹性计算 会员服务 网络 安全 移动云 数加·大数据分析及展现 数加·大数据应用 管理与监控 云通信 阿里云办公 培训与认证 更多
存储与CDN 数据库 域名与网站(万网) 应用服务 数加·人工智能 数加·大数据基础服务 互联网中间件 视频服务 开发者工具 解决方案 物联网 智能硬件
CDN

鉴权代码示例

更新时间:2017-06-07 13:26:11

概述

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("^(http://|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 = "http://"
  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("^(http://|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 = "http://"
  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("^(http://|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 = "http://"
  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 = "http://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 : %s\nAUTH: %s" %(uri, authuri))
  60. if __name__ == "__main__":
  61. main()
本文导读目录