python - 如何在django中启用基本访问认证

标签 python django basic-authentication

我想像这样在我的 Django 项目中启用基本访问身份验证:enter image description here

我找到了 this post通过谷歌,并根据第一个答案更改了我的 settings.py:

MIDDLEWARE_CLASSES = (
  ...

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

  ...
)

AUTHENTICATION_BACKENDS = (
  'django.contrib.auth.backends.RemoteUserBackend',
)

但是认证窗口没有出来。该项目仍处于 Debug模式,我通过 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)

然后,而不是调用 应用程序 = get_wsgi_application() 你应该使用: application = AuthenticationMiddleware(application, "我的用户名", "我的密码")

这将确保对您的 django 服务器的每个请求都经过基本身份验证。 请注意,除非您使用 HTTPS,否则基本身份验证是不安全的,用户凭据将不会被加密。

如果您只想让基本身份验证覆盖您的某些 View ,那么您可以将上述类修改为函数装饰器:

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

然后你可以用它装饰你的 View 以激活基本身份验证。

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

希望对你有帮助

关于python - 如何在django中启用基本访问认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21105822/

相关文章:

python - 了解 maxmin 函数

python - 在Python中从数组中获取特定元素

Django - 跳过数组的第一行

django - 如何使用 ChannelNameRouter 在 Worker 和 Websocket(Django 和 Channels2.x)之间进行通信?

SvelteKit:如何使用 www-authenticate header 保护页面

python - 使用 lxml 处理 XML 中缺失的标签

python - Django 模型表单 - 动态创建字段的顺序

java - HttpUrlConnection 代理身份验证进入重定向循环

spring - 使用Spring Security修改基本身份验证授权流程?

python - 生成postgresql用户密码