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

2024-09-28 19:30:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在我的Django项目中启用基本访问身份验证,如下所示:enter image description here

我在Google找到了this post,并将我的设置.py在第一个答案之后:

MIDDLEWARE_CLASSES = (
  ...

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

  ...
)

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

但是认证窗口没有出来。项目仍处于调试模式,我通过python ./manage.py runserver运行它。在


Tags: 项目django答案pyauth身份验证googlethis
2条回答

我可以想出多种方法来做这件事。如果您希望您的整个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)

然后,不是打电话 应用程序=获取\u wsgi_application() 您应该使用: application=AuthenticationMiddleware(应用程序,“myusername”,“mypassword”)

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

如果只希望基本身份验证覆盖部分视图,则可以将上述类修改为函数修饰符:

^{pr2}$

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

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

希望这有帮助

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

出于调试目的,我建议在管理.py,说:

import os
from django.conf import settings

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

相关问题 更多 >