Python 如何在django中启用基本访问身份验证

Python 如何在django中启用基本访问身份验证,python,django,basic-authentication,Python,Django,Basic Authentication,我希望在Django项目中启用基本访问身份验证,如下所示: 我通过Google找到了,并根据第一个答案更改了我的settings.py: MIDDLEWARE_CLASSES = ( ... 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', ... ) AUTHENTICATION_BACKENDS

我希望在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运行它

如中所述,远程用户由web服务器设置。通常,您需要配置Apache或IIS等web服务器,以使用HTTP基本身份验证保护站点或目录

出于调试目的,我建议在manage.py中设置一个虚拟用户,例如:

import os
from django.conf import settings

if settings.DEBUG:
    os.environ['REMOTE_USER'] = "terry"
如中所述,远程用户由web服务器设置。通常,您需要配置Apache或IIS等web服务器,以使用HTTP基本身份验证保护站点或目录

出于调试目的,我建议在manage.py中设置一个虚拟用户,例如:

import os
from django.conf import settings

if settings.DEBUG:
    os.environ['REMOTE_USER'] = "terry"

我可以想出多种方法来做到这一点。如果您希望整个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\u wsgi\u application() 你应使用: application=AuthenticationMiddleware(应用程序,“我的用户名”、“我的密码”)

这将确保对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
def basic\u auth\u required(func):
@包装(func)
def_装饰器(请求,*args,**kwargs):
从django.contrib.auth导入身份验证,登录
如果request.META.has_key('HTTP_AUTHORIZATION'):
authmeth,auth=request.META['HTTP_AUTHORIZATION'].split('',1)
如果authmeth.lower()=='basic':
auth=auth.strip().decode('base64')
用户名,密码=auth.split(“:”,1)
如果用户名='myusername'和密码='MyPassword':
返回函数(请求、*args、**kwargs)
其他:
返回HttpResponseForbidden(‘禁止’)
res=HttpResponse()
res.status_代码=401
res['WWW-Authenticate']='Basic'
返回res
返回装饰器
然后,您可以用它装饰视图以激活基本身份验证

请注意,在上面的示例中,用户名/密码都是硬编码的。你可以用你自己的机制来代替它


希望这有帮助

我可以想出多种方法来做到这一点。如果您希望整个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\u wsgi\u application() 你应使用: application=AuthenticationMiddleware(应用程序,“我的用户名”、“我的密码”)

这将确保对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
def basic\u auth\u required(func):
@包装(func)
def_装饰器(请求,*args,**kwargs):
从django.contrib.auth导入身份验证,登录
如果request.META.has_key('HTTP_AUTHORIZATION'):
authmeth,auth=request.META['HTTP_AUTHORIZATION'].split('',1)
如果authmeth.lower()=='basic':
auth=auth.strip().decode('base64')
用户名,密码=auth.split(“:”,1)
如果用户名='myusername'和密码='MyPassword':
返回函数(请求、*args、**kwargs)
其他:
返回HttpResponseForbidden(‘禁止’)
res=HttpResponse()
res.status_代码=401
res['WWW-Authenticate']='Basic'
返回res
返回装饰器
然后,您可以用它装饰视图以激活基本身份验证

请注意,在上面的示例中,用户名/密码都是硬编码的。你可以用你自己的机制来代替它


希望这有助于您使用哪台web服务器?@arock它处于调试模式,服务器由
python./manage.py runserver
启动,因此我猜您使用的是哪个web服务器附带的默认服务器?@arock它处于调试模式,服务器由
python./manage.py runserver
启动,所以我想这是Django附带的默认服务器。谢谢你的回答。但它不会阻止其他人在不知道用户名和密码的情况下访问我的网站。在调试模式下应该如何执行?内置服务器不支持基本身份验证。对于您的观点,有类似的变通方法。但是如果你想让其他人使用基本身份验证进行访问,我建议使用合适的web服务器。谢谢你的回答。但它不会阻止其他人在不知道用户名和密码的情况下访问我的网站。在调试模式下应该如何执行?内置服务器不支持基本身份验证。对于您的观点,有类似的变通方法。但如果您希望其他人使用基本身份验证进行访问,我建议使用适当的web服务器。