Sample authentication code

Last Updated: Mar 28, 2017

Overview

The following Python demo provides three authentication methods and describes the composition of requested URLs and hash strings for each method.

For URL authentication rules, see URL Authentication Document.

Python demo

  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()
Thank you! We've received your feedback.