标题几乎概括了我的问题。我想用密码保护位于heroku上的django应用程序中的某些文件。
如果我无法使用htaccess,是否有人对我还可以使用的东西有建议?
谢谢。
最佳答案
正如@mipadi所说,您不能在Heroku上使用htaccess,但可以为此创建一个中间件:
from django.conf import settings
from django.http import HttpResponse
from django.utils.translation import ugettext as _
def basic_challenge(realm=None):
if realm is None:
realm = getattr(settings, 'WWW_AUTHENTICATION_REALM', _('Restricted Access'))
# TODO: Make a nice template for a 401 message?
response = HttpResponse(_('Authorization Required'), mimetype="text/plain")
response['WWW-Authenticate'] = 'Basic realm="%s"' % (realm)
response.status_code = 401
return response
def basic_authenticate(authentication):
# Taken from paste.auth
(authmeth, auth) = authentication.split(' ',1)
if 'basic' != authmeth.lower():
return None
auth = auth.strip().decode('base64')
username, password = auth.split(':',1)
AUTHENTICATION_USERNAME = getattr(settings, 'BASIC_WWW_AUTHENTICATION_USERNAME')
AUTHENTICATION_PASSWORD = getattr(settings, 'BASIC_WWW_AUTHENTICATION_PASSWORD')
return username == AUTHENTICATION_USERNAME and password == AUTHENTICATION_PASSWORD
class BasicAuthenticationMiddleware(object):
def process_request(self, request):
if not getattr(settings, 'BASIC_WWW_AUTHENTICATION', False):
return
if 'HTTP_AUTHORIZATION' not in request.META:
return basic_challenge()
authenticated = basic_authenticate(request.META['HTTP_AUTHORIZATION'])
if authenticated:
return
return basic_challenge()
然后,您需要在
settings.py
中进行定义:BASIC_WWW_AUTHENTICATION_USERNAME = "your user"
BASIC_WWW_AUTHENTICATION_PASSWORD = "your pass"
BASIC_WWW_AUTHENTICATION = True