How to generate a nginx secure link in python

前端 未结 3 1348
迷失自我
迷失自我 2021-01-17 06:41

How do i make the link for the secure link module in nginx using python? I\'m looking to use nginx to serve secured files that have expiring links. Link to Nginx Wiki

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-17 07:39

    The accepted answer is incorrect because it only hashes the secret, not the combination of secret, url, and expiration time.

    import base64
    import hashlib
    import calendar
    import datetime
    
    secret = "itsaSSEEECRET"
    url = "/secure/email-from-your-mom.txt"
    
    future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
    expiry = calendar.timegm(future.timetuple())
    
    secure_link = "{key}{url}{expiry}".format(key=secret,
                                              url=url,
                                              expiry=expiry)
    hash = hashlib.md5(secure_link).digest()
    encoded_hash = base64.urlsafe_b64encode(hash).rstrip('=')
    
    print url + "?st=" + encoded_hash + "&e=" + str(expiry)
    

    Corresponding section of a nginx.conf

    location /secure {
    
        # set connection secure link
        secure_link $arg_st,$arg_e;
        secure_link_md5 "itsaSSEEECRET$uri$secure_link_expires";
    
        # bad hash
        if ($secure_link = "") {
            return 403;
        }
    
        # link expired
        if ($secure_link = "0") {
            return 410;
        }
    
        # do something useful here
    }
    

提交回复
热议问题