django-rest-framework的認證流程源碼簡單解析

  在編寫購物車功能時須要實現未登陸狀態下的添加購物車功能,可是django的認證在進入視圖函數前就會進行,若是未登錄的話請求根本進不到接口(在使用python

JWT驗證的時候),因爲前段會攜帶JWT字段但卻沒有攜帶值,致使認證功能報錯。django

  那麼如何解決呢?函數

  perform_authentication()這個函數是在程序進入視圖函數前運行的spa

def initial(self, request, *args, **kwargs):
        self.format_kwarg = self.get_format_suffix(**kwargs)
        neg = self.perform_content_negotiation(request)
        request.accepted_renderer, request.accepted_media_type = neg
        version, scheme = self.determine_version(request, *args, **kwargs)
        request.version, request.versioning_scheme = version, scheme
        self.perform_authentication(request)  #
        self.check_permissions(request) 
        self.check_throttles(request) 

  這個函數 return request.usercode

  這裏的request.user是個property裝飾的方法orm

@property
    def user(self):
        if not hasattr(self, '_user'):
            self._authenticate()
        return self._user

  

def _authenticate(self):
        for authenticator in self.authenticators:
            try:
                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
                return

        self._not_authenticated()

  其中的self.authenticators是咱們在視圖類中定義的authentication_classes,即身份認證類。對象

  最終,認證類中的authenticate方法會返回一個用戶對象給request.user,咱們的用戶就是這麼得到的。blog

  而在後面的 self.check_permissions(request) 方法,是進行權限驗證的,最終在咱們定義的權限類中的 has_permission 方法返回接口

 return request.user and request.user.is_authenticated

  言歸正傳,若是想實如今不登陸下的進入視圖,那麼咱們只須要重寫perform_authentication()方法,即get

 def perform_authentication(self, request):
        """
        重寫父類的用戶驗證方法,不在進入視圖前就檢查JWT
        """
        pass

  以後再在視圖函數中判斷用戶是否登陸

try:
    user = request.user
except Exception as e:
    user = None
if user and user.is_authenticated:
    """若是用戶登陸的操做"""
else:
    """若是用戶沒登陸的操做"""

 

以上

相關文章
相關標籤/搜索