1. 程式人生 > >Django-Rest-Framework 許可權管理原始碼淺析

Django-Rest-Framework 許可權管理原始碼淺析

許可權管理簡單介紹

在django的views中不論是用類方式還是用裝飾器方式來使用rest框架,django_rest_frame實現許可權管理都需要兩個東西的配合:authentication_classespermission_classes

# 方式1: 裝飾器
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from
rest_framework.permissions import AllowAny from rest_framework.response import Response @api_view(["GET", ]) @permission_classes([AllowAny,]) @authentication_classes([SessionAuthentication, BasicAuthentication]) def test_example(request): content = { 'user': unicode(request.user), # `django.contrib.auth.User` instance.
'auth': unicode(request.auth), # None } return Response(content) # ------------------------------------------------------------ # 方式2: 類 from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import AllowAny from
rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (AllowAny,) def get(self, request, format=None): content = { 'user': unicode(request.user), # `django.contrib.auth.User` instance. 'auth': unicode(request.auth), # None } return Response(content) 複製程式碼

上面給出的是許可權配置的預設方案,寫和不寫沒有區別。rest框架有自己的settings檔案,最原始的預設值都可以在裡面找到:

django-rest預設設定
說道rest的settings檔案,要覆蓋其中的預設行為,特別是許可權認證行為,我們只需要在 專案settings檔案中指定你自己的類即可:

REST_FRAMEWORK = {
    ...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'your_authentication_class_path',
    ),
    ...
}
複製程式碼

在rest的settings檔案中,獲取屬性時,會優先載入專案的settings檔案中的設定,如果專案中沒有的,才載入自己的預設設定:

  • 初始化api_settings物件
api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS)
複製程式碼
  • APISettings類中獲取屬性時優先獲取專案的settings檔案中REST_FRAMEWORK物件的值,沒有的再找自己的預設值
@property
def user_settings(self):
    if not hasattr(self, '_user_settings'):
        # _user_settings預設為載入專案settings檔案中的REST_FRAMEWORK物件
        self._user_settings = getattr(settings, 'REST_FRAMEWORK', {})
    return self._user_settings

def __getattr__(self, attr):
    if attr not in self.defaults:
        raise AttributeError("Invalid API setting: '%s'" % attr)

    try:
        # Check if present in user settings
        # 優先載入user_settings,即專案的settings檔案,沒有就用預設
        val = self.user_settings[attr]
    except KeyError:
        # Fall back to defaults
        val = self.defaults[attr]

    # Coerce import strings into classes
    if attr in self.import_strings:
        val = perform_import(val, attr)

    # Cache the result
    self._cached_attrs.add(attr)
    setattr(self, attr, val)
    return val
複製程式碼

在rest中settings中,能自動檢測專案settings的改變,並重新載入自己的配置檔案:

settings檔案動態載入

許可權管理原理淺析

rest框架是如何使用authentication_classespermission_classes,並將二者配合起來進行許可權管理的呢?

  • 使用類方式實現的時候,我們都會直接或間接的使用到rest框架中的APIVIEW,在urls.py中使用該類的as_view方法來構建router
# views.py
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated


class ExampleAPIView(APIView):
    permission_classes = (IsAuthenticated,)
    ...
    
# -----------------------------
from django.conf.urls import url, include

from .views import ExampleAPIView

urlpatterns = [
    url(r'^example/(?P<example_id>[-\w]+)/examples/?$',
        ExampleAPIView.as_view()),
]

複製程式碼
  • 在我們呼叫APIVIEW.as_view()的時候,該類會呼叫父類的同名方法:

    呼叫父類同名方法

  • 父類的同名方法中,呼叫了dispatch方法:

    此處輸入圖片的描述

  • rest ***重寫***了該方法,在該方法中對requset做了一次服務端初始化(加入驗證資訊等)處理

    重寫dispatch,處理requset
    呼叫許可權管理
    此處輸入圖片的描述

在許可權管理中會使用預設的或是你指定的許可權認證進行驗證: 這裡只是做驗證並存儲驗證結果,這裡操作完後authentication_classes的作用就完成了。驗證結果會在後面指定的permission_classes中使用!

    def get_authenticators(self):
        """
        Instantiates and returns the list of authenticators that this view can use.
        """
        return [auth() for auth in self.authentication_classes]
複製程式碼

通過指定的permission_classes確定是否有當前介面的訪問許可權:

class IsAuthenticatedOrReadOnly(BasePermission):
    """
    The request is authenticated as a user, or is a read-only request.
    """

    def has_permission(self, request, view):
        return (
            request.method in SAFE_METHODS or
            request.user and
            request.user.is_authenticated
        )
複製程式碼

最後,不管有沒有使用permission_classes來決定是否能訪問,預設的或是你自己指定的authentication_classes都會執行並將許可權結果放在request中!