python django 1.4 如何设置两个 WWW-Authenticate http header

标签 python django authentication

我正在开发小型 Intranet Web 服务。我希望通过 MS AD 中的 kerberos 或基本身份验证对用户进行身份验证。因此,我需要在响应 401 中设置两个“WWW-Authenticate”http header 。我如何使用 Django 来做到这一点?

应该是这样的:

Client: GET www/index.html

Server: HTTP/1.1 401 Unauthorized
        WWW-Authenticate: Negotiate
        WWW-Authenticate: Basic realm="corp site"

此代码覆盖 header

def auth(request):
    response = None
    auth = request.META.get('HTTP_AUTHORIZATION')
    if not auth:
        response = HttpResponse(status = 401)
        response['WWW-Authenticate'] = 'Negotiate'
        response['WWW-Authenticate'] = 'Basic realm="  trolls place basic auth"'

    elif auth.startswith('Negotiate YII'):
        ...

    return response

最佳答案

我想中间件最适合这项任务,但如果您有其他想法,这里是调整为与您的 View 一起使用的中间件代码(如果您决定,您仍然可以很容易地将其变成中间件)这样做):

from django.conf import settings
from django.http import HttpResponse

def basic_challenge(realm=None):
    if realm is None:
        realm = getattr(settings,
                        'WWW_AUTHENTICATION_REALM',
                        'Restricted Access')
    response = HttpResponse('Authorization Required',
                            mimetype="text/plain")
    response['WWW-Authenticate'] = 'Basic realm="%s"' % (realm)
    response.status_code = 401
    return response

def basic_authenticate(authentication):
    (authmeth, auth) = authentication.split(' ', 1)
    if 'basic' != authmeth.lower():
        return None

    auth = auth.strip().decode('base64')
    username, password = auth.split(':', 1)
    AUTHENTICATION_USERNAME = getattr(settings,
                                      'BASIC_WWW_AUTHENTICATION_USERNAME')
    AUTHENTICATION_PASSWORD = getattr(settings,
                                      'BASIC_WWW_AUTHENTICATION_PASSWORD')
    return (username == AUTHENTICATION_USERNAME and
            password == AUTHENTICATION_PASSWORD)

def auth_view(request):
    auth = request.META.get('HTTP_AUTHORIZATION', '')

    if auth.startswith('Negotiate YII'):
        pass
    elif auth:
        if basic_authenticate(auth):
            #successfully authenticated
            pass
        else:
            return basic_challenge()

    # nothing matched, still return basic challange
    return basic_challenge()

关于python django 1.4 如何设置两个 WWW-Authenticate http header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21228527/

相关文章:

authentication - Nodejs,通过https进行身份验证并重定向到http

c# - 如何获取用户输入以使用登录控制台应用程序的验证方法?

python - 将整数数组转换为索引字典

python - Python中分组数据的累积自定义函数

python - 根据条件更改窗口 pyspark 数据框中的所有行值

python - Hook 到 django 字段分配

python - 当表单验证错误发生时,我如何指定它们?

Python:从 ADLS 文件夹中查找重命名并移动 JSON 文件

django - Elasticsearch 查询

authentication - 识别匿名用户