Prevent A User From Downloading Files from Python?
I am working on a project that requires password protected downloading, but I'm not exactly sure how to implement that. I开发者_Python百科f the target file has a specific extension (.exe, .mp3, .mp4, etc), I want to prompt the user for a username and password. Any ideas on this?
I am using Python 26 on Windows XP.
This is best implemented at the web server level.
If you are using Apache, this can be done by placing the files you desire to protect in a directory with an htaccess
file which requires user authentication.
Then, implement HTTP Basic Auth in your Python script to download the files. Make sure to use an SSL connection; basic auth sends the user's password over the wire in the clear.
Use HTTP's basic authentication (shown in the URL I've quoted from the client side):
- whenever a "sensitive" page or file is requested, and no Authorization header is part
of the request (or it's invalid, see below), return a 401 status code instead,
with a header
WWW-Authenticate: Basic realm=XXXX
(where XXXX is a hash of the URL, e.g. with MD5 or SHA1, to make it essentially unique per-file) the user will then need to enter username and password at his browser, which will send them back to the server you're implementing with the simple algorithm shown at that URL, namely:
import base64 base64string = base64.encodestring('%s:%s' % (username, password))[:-1] req.add_header("Authorization", "Basic %s" % base64string)
when the Authorization header is present in the request, decode the base64 string it presents after
'Basic '
and check that it has theusername:password
you want
You can use more sophisticated authentication, of course, but this may get you started unless the user's connection can (or so you suspect) be "sniffed" by evil third parties (in which case you'll want to use HTTPS anyway, so that basic auth becomes OK again;-).
精彩评论