我正在开发小型 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/