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

Ter*_*rry 3 python django basic-authentication

我想在我的 Django 项目中启用基本访问身份验证,如下所示:在此输入图像描述

我通过 Google 找到了这篇文章,并根据第一个答案更改了我的 settings.py:

MIDDLEWARE_CLASSES = (
  ...

  'django.contrib.auth.middleware.AuthenticationMiddleware',
  'django.contrib.auth.middleware.RemoteUserMiddleware',

  ...
)

AUTHENTICATION_BACKENDS = (
  'django.contrib.auth.backends.RemoteUserBackend',
)
Run Code Online (Sandbox Code Playgroud)

但身份验证窗口没有出现。该项目仍处于调试模式,我通过python ./manage.py runserver.

ely*_*nch 5

我可以想出多种方法来做到这一点。如果您希望整个 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)
Run Code Online (Sandbox Code Playgroud)

然后,您应该使用: application = AuthenticationMiddleware(application, "myusername", "mypassword") 而不是调用 application = get_wsgi_application()

这将确保对 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
Run Code Online (Sandbox Code Playgroud)

然后您可以用它来装饰您的视图以激活基本身份验证。

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

希望这可以帮助