我正在开发小型Intranet Web服务。我想通过MS AD或基本身份验证中的kerberos对用户进行身份验证。因此,我需要在响应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"
此代码覆盖标头
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
最佳答案
我想中间件将是完成此任务的最佳选择,但是如果您有其他想法,请调整中间件代码以使其适合您的视图(如果您决定这样做,则可以很容易地将其转换为中间件) :
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()