restful framework 認證源碼流程
一、請求到來之後,都要先執行dispatch方法,dispatch方法方法根據請求方式的不同觸發get/post/put/delete等方法
註意,APIView中的dispatch方法有很多的功能
def dispatch(self, request, *args, **kwargs): """ `.dispatch()` is pretty much the same as Django‘s regular dispatch, but with extra hooks for startup, finalize, and exception handling.""" self.args = args self.kwargs = kwargs 第一步:對request進行加工(添加數據) request = self.initialize_request(request, *args, **kwargs) self.request = request self.headers = self.default_response_headers # deprecate? try: #第二步: #處理版權信息 #認證 #權限 #請求用戶進行訪問頻率的限制 self.initial(request, *args, **kwargs) # Get the appropriate handler method if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed)else: handler = self.http_method_not_allowed # 第三步、執行:get/post/put/delete函數 response = handler(request, *args, **kwargs) except Exception as exc: response = self.handle_exception(exc) #第四步、 對返回結果再次進行加工 self.response = self.finalize_response(request, response, *args, **kwargs) return self.response
二、上面是大致步驟,下面我們來具體分析一下,看每個步驟中都具體幹了什麽事
1、對request進行加工(添加數據)
我們來看看request裏面都添加了那些數據
a、首先 request = self.initialize_request(request, *args, **kwargs)點進去,會發現:在Request裏面多加了四個,如下
def initialize_request(self, request, *args, **kwargs): """ Returns the initial request object. """ #吧請求弄成一個字典返回了 parser_context = self.get_parser_context(request) return Request( request, parsers=self.get_parsers(), #解析數據,默認的有三種方式,可點進去看 #self.get_authenticator優先找自己的,沒有就找父類的 authenticators=self.get_authenticators(), #獲取認證相關的所有類並實例化,傳入request對象供Request使用 negotiator=self.get_content_negotiator(), parser_context=parser_context )
b、獲取認證相關的類的具體 authenticators=self.get_authenticators(),
def get_authenticators(self): """ Instantiates and returns the list of authenticators that this view can use. """ #返回的是對象列表 return [auth() for auth in self.authentication_classes] #[SessionAuthentication,BaseAuthentication]
c、查看認證的類:self.authentication_classes
authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES #默認的,如果自己有會優先執行直接的
d、接著走進api_settings
api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS) #點擊繼承的DEFAULTS類
DEFAULTS = { # Base API policies ‘DEFAULT_AUTHENTICATION_CLASSES‘: ( ‘rest_framework.authentication.SessionAuthentication‘, #這時候就找到了他默認認證的類了,可以導入看看 ‘rest_framework.authentication.BasicAuthentication‘ ),
e、導入了類看看類裏面具體幹了什麽
from rest_framework.authentication import SessionAuthentication from rest_framework.authentication import BaseAuthentication
f、看到裏面有個authenticate方法和authenticate_header方法
class BaseAuthentication(object): """ All authentication classes should extend BaseAuthentication. """ def authenticate(self, request): """ Authenticate the request and return a two-tuple of (user, token). """ raise NotImplementedError(".authenticate() must be overridden.") def authenticate_header(self, request): """ Return a string to be used as the value of the `WWW-Authenticate` header in a `401 Unauthenticated` response, or `None` if the authentication scheme should return `403 Permission Denied` responses. """ pass
具體處理認證,從headers裏面能獲取用戶名和密碼
class BasicAuthentication(BaseAuthentication): """ HTTP Basic authentication against username/password. """ www_authenticate_realm = ‘api‘ def authenticate(self, request): """ Returns a `User` if a correct username and password have been supplied using HTTP Basic authentication. Otherwise returns `None`. """ auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b‘basic‘: return None #返回none不處理。讓下一個處理 if len(auth) == 1: msg = _(‘Invalid basic header. No credentials provided.‘) raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = _(‘Invalid basic header. Credentials string should not contain spaces.‘) raise exceptions.AuthenticationFailed(msg) try: auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(‘:‘) #用partition切割冒號也包括 except (TypeError, UnicodeDecodeError, binascii.Error): msg = _(‘Invalid basic header. Credentials not correctly base64 encoded.‘) raise exceptions.AuthenticationFailed(msg) userid, password = auth_parts[0], auth_parts[2] # 返回用戶和密碼 return self.authenticate_credentials(userid, password, request) def authenticate_credentials(self, userid, password, request=None): """ Authenticate the userid and password against username and password with optional request for context. """ credentials = { get_user_model().USERNAME_FIELD: userid, ‘password‘: password } user = authenticate(request=request, **credentials) if user is None: raise exceptions.AuthenticationFailed(_(‘Invalid username/password.‘)) if not user.is_active: raise exceptions.AuthenticationFailed(_(‘User inactive or deleted.‘)) return (user, None) def authenticate_header(self, request): return ‘Basic realm="%s"‘ % self.www_authenticate_realm
g、當然restfulframework默認定義了兩個類。我們也可以自定制類,自己有就用自己的了,自己沒有就去找父類的了,但是裏面必須實現authenticate方法,不然會報錯。
2、進行一下操作
- 處理版權信息
- 認證
- 權限
- 請求用戶進行訪問頻率的限制
我們主要來看一下認證流程
認證流程:
a、首先 self.initial(request, *args, **kwargs)可以看到做了以下操作
def initial(self, request, *args, **kwargs): """ Runs anything that needs to occur prior to calling the method handler. """ self.format_kwarg = self.get_format_suffix(**kwargs) # Perform content negotiation and store the accepted info on the request neg = self.perform_content_negotiation(request) request.accepted_renderer, request.accepted_media_type = neg # Determine the API version, if versioning is in use. #2.1 處理版本信息 version, scheme = self.determine_version(request, *args, **kwargs) request.version, request.versioning_scheme = version, scheme # Ensure that the incoming request is permitted #2.2 認證 self.perform_authentication(request) # 2.3 權限 self.check_permissions(request) # 2.4 請求用戶進行訪問頻率的限制 self.check_throttles(request)
b、我們先來看認證,self.perform_authentication(request) 具體幹了什麽,按住ctrl點擊進去
def perform_authentication(self, request): """ Perform authentication on the incoming request. Note that if you override this and simply ‘pass‘, then authentication will instead be performed lazily, the first time either `request.user` or `request.auth` is accessed. """ request.user #執行request的user,這是的request已經是加工後的request了
c、那麽我們可以從視圖裏面導入一下Request,找到request對象的user方法
from rest_framework.views import Request
@property def user(self): """ Returns the user associated with the current request, as authenticated by the authentication classes provided to the request. """ if not hasattr(self, ‘_user‘): with wrap_attributeerrors(): self._authenticate() # return self._user #返回user
d、執行self._authenticate() 開始用戶認證,如果驗證成功後返回元組: (用戶,用戶Token)
def _authenticate(self): """ Attempt to authenticate the request using each authentication instance in turn. """ #循環對象列表 for authenticator in self.authenticators: try: #執行每一個對象的authenticate 方法 user_auth_tuple = authenticator.authenticate(self) except exceptions.APIException: self._not_authenticated() raise if user_auth_tuple is not None: self._authenticator = authenticator self.user, self.auth = user_auth_tuple #返回一個元組,user,和auth,賦給了self, # 只要實例化Request,就會有一個request對象,就可以request.user,request.auth了 return self._not_authenticated()
e、在user_auth_tuple = authenticator.authenticate(self) 進行驗證,如果驗證成功,執行類裏的authenticatie方法
f、如果用戶沒有認證成功:self._not_authenticated()
def _not_authenticated(self): """ Set authenticator, user & authtoken representing an unauthenticated request. Defaults are None, AnonymousUser & None. """ #如果跳過了所有認證,默認用戶和Token和使用配置文件進行設置 self._authenticator = None # if api_settings.UNAUTHENTICATED_USER: self.user = api_settings.UNAUTHENTICATED_USER() # 默認值為:匿名用戶AnonymousUser else: self.user = None # None 表示跳過該認證 if api_settings.UNAUTHENTICATED_TOKEN: self.auth = api_settings.UNAUTHENTICATED_TOKEN() # 默認值為:None else: self.auth = None # (user, token) # 表示驗證通過並設置用戶名和Token; # AuthenticationFailed異常
3、執行get/post/delete等方法
4、對返回結果在進行加工
restful framework 認證源碼流程