2014-10-30 15 views
0

我的Django的REST API擁有此類認證:流量在Django

class AuthView(APIView): 
     authentication_classes = (BasicAuthentication,) 

     def post(self, request, *args, **kwargs): 
      login(request, request.user) 
      data = {'testkey':'testvalue'} 
      return HttpResponse(json.dumps(data), content_type="application/json") 

當憑據正確,控制要發佈的方法(這是罰款)。 但是,對於不正確的憑據,是否有人可以解釋爲什麼控制不會進入post方法?

我想爲未經驗證的請求設置一個自定義HTTP狀態代碼(無法在帖子內部這樣做,因爲控制不會去那裏查看未經驗證的請求),並且正在尋找一種合適的方法來實現這一點。

回答

0

最後我伸出BasicAuthentication和被覆蓋的authenticate_credentials方法是這樣的:

from rest_framework.authentication import BasicAuthentication 
from django.contrib.auth import authenticate 

class CustomAuth(BasicAuthentication): 

    def authenticate_credentials(self, userid, password): 
     """ 
     Override authenticate_credentials(..) of BasicAuthentication 
     """ 
     user = authenticate(username=userid, password=password) 
     '''if user is None or not user.is_active: 
      raise exceptions.AuthenticationFailed('Invalid username/password')''' 
     return (user, None) 

這似乎是工作的罰款現在。 但是,我不確定這是否是這樣做的最好方法!

-1

基本驗證通常由瀏覽器實現。我希望他們只在驗證通過後才提交帖子。

http://tools.ietf.org/html/rfc1945#section-11.1

+0

這裏的邏輯全部發生在正在處理請求的Django Rest Framework中,只有在身份驗證通過的情況下才會調用post方法(幸運的是,否則它會很容易忽略身份驗證)。 – 2014-10-30 22:41:59

1

控制永遠不會進入你的POST方法,因爲Django的REST框架(它使用的是這裏)將使用您所指定的authentication_classes進入post方法(或get等之前首先驗證傳入的請求, - 取決於請求)。

您在此處使用的BasicAuthenticationthrows an exception when credentials are incorrect(即Django Rest Framework的工作方式,如documented here)。

這將停止執行流程(以便它永遠不會到達您的方法),並提前返回錯誤代碼。


現在,實現此功能的實際代碼位於APIView.dispatch中,在發出請求時會調用該代碼。 self.initial()呼叫是最終調用認證碼的呼叫,而調用post方法的呼叫是handler(...)線路(稍後會發生,如您所見)。


爲了回答你問題的第二部分,Django的REST框架是很自以爲是的事情應該怎麼做,但你也許可以通過定義自己的身份驗證類以自定義的狀態代碼,但我對此表示懷疑。

+0

我擴展BasicAuthentication以覆蓋authenticate_credentials方法(Plz請參閱下面的答案),這似乎工作正常。 但是,這是做到這一點的正確方法還是會有任何副作用? – 2014-10-31 04:53:05