2014-01-20 60 views
1

我正在開發小型Intranet Web服務。我想通過MS AD中的Kerberos或基本身份驗證來驗證用戶身份。出於這個原因,我需要在響應401中設置兩個'WWW-Authenticate'http標頭。我如何使用Django來做到這一點?python django 1.4如何設置兩個WWW-Authenticate http標頭

應該是這樣的:

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 

回答

1

我猜中間件將是最適合這個任務,但如果你心裏有別的東西,在這裏是中間件代碼調整以適合您的視圖(如果您決定這樣做,您可以非常容易地將其轉換爲中間件):

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

關於中間件的好主意,但無論如何,我想發送一個HTTP 401響應兩個頭'WWW身份驗證'**我該怎麼做? –

+0

嗯我沒有仔細閱讀這個問題,我得到的印象你只需要基本的認證,對不起:) – andrean