pythonDjango1.4如何设置两个WWWAuthenticate http头

2024-10-03 04:37:46 发布

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

Im正在开发小型intranet web服务。我想要在msad中通过kerberos对用户进行身份验证,或者使用basic auth。因此,我需要在响应401中设置两个“WWW Authenticate”http头。我怎么能用Django做呢?在

应该是这样的:

Client: GET www/index.html

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

此代码覆盖标头

^{pr2}$

Tags: django用户clientauth身份验证webhttpget
1条回答
网友
1楼 · 发布于 2024-10-03 04:37:46

我想中间件对于这个任务来说是最好的,但是如果您有其他想法,这里是中间件代码调整为适合您的视图(如果您决定这样做,您仍然可以很容易地将其转换为中间件):

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()

相关问题 更多 >