在上一篇博客中已經介紹了django rest framework 對於認證的源碼流程,以及實現過程,當用戶經過認證之後下一步就是涉及到許可權的問題。比如訂單的業務只能VIP才能查看,所以這時候需要對許可權進行控制。下麵將介紹DRF的許可權控制源碼剖析。 這裡繼續使用之前的示例,加入相應的許可權,這裡先介紹 ...
一、簡介 |
在上一篇博客中已經介紹了django rest framework 對於認證的源碼流程,以及實現過程,當用戶經過認證之後下一步就是涉及到許可權的問題。比如訂單的業務只能VIP才能查看,所以這時候需要對許可權進行控制。下麵將介紹DRF的許可權控制源碼剖析。
二、基本使用 |
這裡繼續使用之前的示例,加入相應的許可權,這裡先介紹使用示例,然後在分析許可權源碼
1.在django 項目下新建立目錄utils,並建立permissions.py,添加許可權控制:
class MyPremission(object): message = "您不是會員無權訪問" def has_permission(self,request,view): if request.user.user_type == 1: ## user_type 為1代表普通用戶,則不能查看 return False return True
2.在訂單視圖中使用
class OrderView(APIView): '''查看訂單''' from utils.permissions import MyPremission authentication_classes = [Authentication,] #添加認證 permission_classes = [MyPremission,] #添加許可權 def get(self,request,*args,**kwargs): #request.user #request.auth ret = {'code':1000,'msg':"你的訂單已經完成",'data':"買了一個mac"} return JsonResponse(ret,safe=True)
urls.py
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^api/v1/auth', views.AuthView.as_view()), url(r'^api/v1/order', views.OrderView.as_view()), ]
models.py
from django.db import models class UserInfo(models.Model): user_type_choice = ( (1,"普通用戶"), (2,"會員"), ) user_type = models.IntegerField(choices=user_type_choice) username = models.CharField(max_length=32,unique=True) password = models.CharField(max_length=64) class UserToken(models.Model): user = models.OneToOneField(to=UserInfo) token = models.CharField(max_length=64)
3.驗證:訂單業務同樣使用user_type=1的用戶進行驗證,這裡使用工具postman發送請求驗證,結果如下:證明我們的許可權生效了。
三、許可權源碼剖析 |
1.同樣請求到達視圖時候,先執行APIView的dispatch方法,以下源碼是我們在認證篇已經解讀過了:
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( # request, # parsers=self.get_parsers(), # authenticators=self.get_authenticators(), # negotiator=self.get_content_negotiator(), # parser_context=parser_context # ) #request(原始request,[BasicAuthentications對象,]) #獲取原生request,request._request #獲取認證類的對象,request.authticators #1.封裝request request = self.initialize_request(request, *args, **kwargs) self.request = request self.headers = self.default_response_headers # deprecate? try: #2.認證 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 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
2.執行inital方法,initial方法中執行perform_authentication則開始進行認證
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. version, scheme = self.determine_version(request, *args, **kwargs) request.version, request.versioning_scheme = version, scheme # Ensure that the incoming request is permitted #4.實現認證 self.perform_authentication(request) #5.許可權判斷 self.check_permissions(request) self.check_throttles(request)
3.當執行完perform_authentication方法認證通過時候,這時候就進入了本篇文章主題--許可權(check_permissions方法),下麵是check_permissions方法源碼:
def check_permissions(self, request): """ Check if the request should be permitted. Raises an appropriate exception if the request is not permitted. """ for permission in self.get_permissions(): #迴圈對象get_permissions方法的結果,如果自己沒有,則去父類尋找, if not permission.has_permission(request, self): #判斷每個對象中的has_permission方法返回值(其實就是許可權判斷),這就是為什麼我們需要對許可權類定義has_permission方法 self.permission_denied( request, message=getattr(permission, 'message', None) #返回無許可權信息,也就是我們定義的message共有屬性 )
4.從上源碼中我們可以看出,perform_authentication方法中迴圈get_permissions結果,並逐一判斷許可權,所以需要分析get_permissions方法返回結果,以下是get_permissions方法源碼:
def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ return [permission() for permission in self.permission_classes] #與許可權一樣採用列表生成式獲取每個認證類對象
5.get_permissions方法中尋找許可權類是通過self.permission_class欄位尋找,和認證類一樣預設該欄位在全局也有配置,如果我們視圖類中已經定義,則使用我們自己定義的類。
class APIView(View): # The following policies may be set at either globally, or per-view. renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES parser_classes = api_settings.DEFAULT_PARSER_CLASSES authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES #許可權控制 content_negotiation_class = api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS metadata_class = api_settings.DEFAULT_METADATA_CLASS versioning_class = api_settings.DEFAULT_VERSIONING_CLASS
6.承接check_permissions方法,當認證類中的has_permission()方法返回false時(也就是認證不通過),則執行self.permission_denied(),以下是self.permission_denied()源碼:
def permission_denied(self, request, message=None): """ If request is not permitted, determine what kind of exception to raise. """ if request.authenticators and not request.successful_authenticator: raise exceptions.NotAuthenticated() raise exceptions.PermissionDenied(detail=message) # 如果定義了message屬性,則拋出屬性值
7.認證不通過,則至此django rest framework的許可權源碼到此結束,相對於認證源碼簡單一些。
四、內置許可權驗證類 |
django rest framework 提供了內置的許可權驗證類,其本質都是定義has_permission()方法對許可權進行驗證:
#路徑:rest_framework.permissions ##基本許可權驗證 class BasePermission(object) ##允許所有 class AllowAny(BasePermission) ##基於django的認證許可權,官方示例 class IsAuthenticated(BasePermission): ##基於django admin許可權控制 class IsAdminUser(BasePermission) ##也是基於django admin class IsAuthenticatedOrReadOnly(BasePermission) .....
五、總結 |
1.使用方法:
- 繼承BasePermission類(推薦)
- 重寫has_permission方法
- has_permission方法返回True表示有權訪問,False無權訪問
2.配置:
###全局使用 REST_FRAMEWORK = { #許可權 "DEFAULT_PERMISSION_CLASSES":['API.utils.permission.MyPremission'], } ##單一視圖使用,為空代表不做許可權驗證 permission_classes = [MyPremission,] ###優先順序 單一視圖>全局配置