我想在我的Django项目中启用基本访问身份验证,如下所示:
我通过Google找到了此信息,并按照第一个答案更改了settings.py:
MIDDLEWARE_CLASSES = (
...
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.RemoteUserMiddleware',
...
)
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.RemoteUserBackend',
)
但是身份验证窗口没有出现。该项目仍处于调试模式,我通过运行它python ./manage.py runserver
。
我可以想到多种方法来做到这一点。如果您希望整个django应用程序都受到基本身份验证的保护,则可以向wsgi应用程序添加身份验证中间件。Django在您的项目中创建一个默认的wsgi应用程序。将以下中间件添加到此wsgi.py文件:
class AuthenticationMiddleware(object):
def __init__(self, app, username, password):
self.app = app
self.username = username
self.password = password
def __unauthorized(self, start_response):
start_response('401 Unauthorized', [
('Content-type', 'text/plain'),
('WWW-Authenticate', 'Basic realm="restricted"')
])
return ['You are unauthorized and forbidden to view this resource.']
def __call__(self, environ, start_response):
authorization = environ.get('HTTP_AUTHORIZATION', None)
if not authorization:
return self.__unauthorized(start_response)
(method, authentication) = authorization.split(' ', 1)
if 'basic' != method.lower():
return self.__unauthorized(start_response)
request_username, request_password = authentication.strip().decode('base64').split(':', 1)
if self.username == request_username and self.password == request_password:
return self.app(environ, start_response)
return self.__unauthorized(start_response)
然后,而不是调用application = get_wsgi_application(),应使用:application = AuthenticationMiddleware(application,“ myusername”,“ mypassword”)
这将确保对django服务器的每个请求都经过基本身份验证。请注意,除非您使用HTTPS,否则基本身份验证是不安全的,并且用户凭据将不会被加密。
如果您只希望基本身份验证涵盖某些视图,则可以将上述类修改为函数装饰器:
def basic_auth_required(func):
@wraps(func)
def _decorator(request, *args, **kwargs):
from django.contrib.auth import authenticate, login
if request.META.has_key('HTTP_AUTHORIZATION'):
authmeth, auth = request.META['HTTP_AUTHORIZATION'].split(' ', 1)
if authmeth.lower() == 'basic':
auth = auth.strip().decode('base64')
username, password = auth.split(':', 1)
if username=='myusername' and password == 'my password':
return func(request, *args, **kwargs)
else:
return HttpResponseForbidden('<h1>Forbidden</h1>')
res = HttpResponse()
res.status_code = 401
res['WWW-Authenticate'] = 'Basic'
return res
return _decorator
然后,您可以以此来装饰视图以激活基本身份验证。
请注意,在上面的示例中,用户名/密码都是硬编码的。您可以用自己的机制替换它。
希望这可以帮助
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句