开发者

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):

  1. 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)
  2. 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)

  3. when the Authorization header is present in the request, decode the base64 string it presents after 'Basic ' and check that it has the username: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;-).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜