DRF框架(七) ——三大認證組件之頻率組件、jwt認證


drf頻率組件源碼

1.APIView的dispatch方法的  self.initial(request,*args,**kwargs)  點進去

2.self.check_throttles(request)  進行頻率認證

    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
        self.perform_authentication(request)
        self.check_permissions(request)
        self.check_throttles(request) #頻率認證

3.self.get_throttles()  頻率組件最終要的兩個方法:allow_request()和wait()

    def check_throttles(self, request):  #頻率組件核心代碼 """
        Check if request should be throttled.
        Raises an appropriate exception if the request is throttled.
        """
        throttle_durations = []
        for throttle in self.get_throttles():
            if not throttle.allow_request(request, self):
                throttle_durations.append(throttle.wait())

3-1. self.throttle_classes  出現頻率配置settings信息,經過查詢源碼的settings文件對頻率配置為空

    def get_throttles(self):
        """
        Instantiates and returns the list of throttles that this view uses.
        """
        return [throttle() for throttle in self.throttle_classes]  #頻率組件配置信息

4. allow_request() 在自身、所在類都沒有找到,那去父類找,在源碼throttling.py中

class SimpleRateThrottle(BaseThrottle):
   
    cache = default_cache
    timer = time.time
    cache_format = 'throttle_%(scope)s_%(ident)s'
    scope = None
    THROTTLE_RATES = api_settings.DEFAULT_THROTTLE_RATES

    def __init__(self):
        if not getattr(self, 'rate', None):
            self.rate = self.get_rate()  #3.rate值就是方法get_rate的返回值(頻率次數)
        self.num_requests, self.duration = self.parse_rate(self.rate)

    def get_cache_key(self, request, view):
        raise NotImplementedError('.get_cache_key() must be overridden')

  #get_rate最后返回的結果是設置的頻率次數
def get_rate(self):#1.在自定義類中要給scope屬性賦值 if not getattr(self, 'scope', None): msg = ("You must set either `.scope` or `.rate` for '%s' throttle" % self.__class__.__name__) raise ImproperlyConfigured(msg) try: return self.THROTTLE_RATES[self.scope] #2.在settings文件中配置scope屬性值對應的value except KeyError: msg = "No default throttle rate set for '%s' scope" % self.scope raise ImproperlyConfigured(msg) def parse_rate(self, rate): if rate is None: return (None, None) num, period = rate.split('/') #4.rate有值,根據源碼,自定義的rate值是一個字符串,而且是這種格式:'數字/以s,m,h,d之類開頭的字母' num_requests = int(num) #5.獲得的數字就是設置的頻率次數 duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[0]] #6.獲得是間隔的時間(以秒為單位) return (num_requests, duration) #7.數據返回給__init__,解壓賦值 def allow_request(self, request, view): if self.rate is None: return True            #get_cache_key就是要重寫的方法,若不重寫,會直接拋出異常 self.key = self.get_cache_key(request, view) #8.自定義的時候需要重寫的方法,有返回值,放入緩存中 if self.key is None: return True self.history = self.cache.get(self.key, []) #9.獲取緩存,通過key取值 self.now = self.timer() #10.當前時間 # Drop any requests from the history which have now passed the # throttle duration while self.history and self.history[-1] <= self.now - self.duration: self.history.pop() if len(self.history) >= self.num_requests: return self.throttle_failure() return self.throttle_success() def throttle_success(self): self.history.insert(0, self.now) self.cache.set(self.key, self.history, self.duration) return True def throttle_failure(self): return False
  #返回距下一次能請求的時間,限制的訪問次數在parse_rate可以求出
def wait(self): """ Returns the recommended next request time in seconds. """ if self.history: remaining_duration = self.duration - (self.now - self.history[-1]) else: remaining_duration = self.duration available_requests = self.num_requests - len(self.history) + 1 if available_requests <= 0: return None return remaining_duration / float(available_requests)

核心源碼分析

def check_throttles(self, request):
    throttle_durations = []
    # 1)遍歷配置的頻率認證類,初始化得到一個個頻率認證類對象(會調用頻率認證類的 __init__() 方法)
    # 2)頻率認證類對象調用 allow_request 方法,判斷是否限次(沒有限次可訪問,限次不可訪問)
    # 3)頻率認證類對象在限次后,調用 wait 方法,獲取還需等待多長時間可以進行下一次訪問
    # 注:頻率認證類都是繼承 SimpleRateThrottle 類
    for throttle in self.get_throttles():
        if not throttle.allow_request(request, self):
            # 只要頻率限制了,allow_request 返回False了,才會調用wait
            throttle_durations.append(throttle.wait())

            if throttle_durations:
                # Filter out `None` values which may happen in case of config / rate
                # changes, see #1438
                durations = [
                    duration for duration in throttle_durations
                    if duration is not None
                ]

                duration = max(durations, default=None)
                self.throttled(request, duration)

注意:

主要流程在第四步中標出

自定義頻率類

# 1) 自定義一個繼承 SimpleRateThrottle 類 的頻率類
# 2) 設置一個 scope 類屬性,屬性值為任意見名知意的字符串
# 3) 在settings配置文件中,配置drf的DEFAULT_THROTTLE_RATES,格式為 {scope字符串值: '次數/時間'}
# 4) 在自定義頻率類中重寫 get_cache_key 方法
    # 限制的對象返回 與限制信息有關的字符串
    # 不限制的對象返回 None (只能放回None,不能是False或是''等)

寫一個短信接口,設置  1/min頻率限制

utils.throttles.py

from rest_framework.throttling import SimpleRateThrottle

class SMSRateThrottle(SimpleRateThrottle):
    scope = 'sms'

    #只對提交手機號的get方法進行限制
    def get_cache_key(self, request, view):
        mobile = request.query_params.get('mobile')
        #沒有手機號就不做頻率限制
        if not mobile:
            return None
        #返回的信息可以用手機號動態變化,且不易重復的字符串,作為緩存的key
        return 'throttle_%(scope)s_%(ident)s' % {'scope': self.scope, 'ident': mobile}

settings.py配置:

# drf配置
REST_FRAMEWORK = {
    # 頻率限制條件配置
    'DEFAULT_THROTTLE_RATES': {
        'sms': '1/min'
    },
}

視圖層:views.py

from .throttles import SMSRateThrottle
class TestSMSAPIView(APIView):
    # 局部配置頻率認證
    throttle_classes = [SMSRateThrottle]
    def get(self, request, *args, **kwargs):
        return APIResponse(0, 'get 獲取驗證碼 OK')
    def post(self, request, *args, **kwargs):
        return APIResponse(0, 'post 獲取驗證碼  OK')

路由:urls.py

url(r'^sms/$', views.TestSMSAPIView.as_view()),

會限制的接口

# 只會對 /api/sms/?mobile=具體手機號 接口才會有頻率限制,設置了限制頻率,到達訪問次數就會禁止
# 1)對 /api/sms/ 或其他接口發送無限制
# 2)對數據包提交mobile的/api/sms/接口無限制
# 3)對不是mobile(如phone)字段提交的電話接口無限制

 

JWT認證

優點

1) 服務器不要存儲token,token交給每一個客戶端自己存儲,服務器壓力小
2)服務器存儲的是 簽發和校驗token 兩段算法,簽發認證的效率高
3)算法完成各集群服務器同步成本低,路由項目完成集群部署(適應高並發)

格式

1) jwt token采用三段式:頭部.載荷.簽名 2)每一部分都是一個json字典加密形參的字符串
3)頭部和載荷采用的是base64可逆加密(前台后台都可以解密)
4)簽名采用hash256不可逆加密(后台校驗采用碰撞校驗)
5)各部分字典的內容:
    頭部:基礎信息 - 公司信息、項目組信息、可逆加密采用的算法
    載荷:有用但非私密的信息 - 用戶可公開信息、過期時間
    簽名:頭部+載荷+秘鑰 不可逆加密后的結果
    注:服務器jwt簽名加密秘鑰一定不能泄露
    
簽發token:固定的頭部信息加密.當前的登陸用戶與過期時間加密.頭部+載荷+秘鑰生成不可逆加密
校驗token:頭部可校驗也可以不校驗,載荷校驗出用戶與過期時間,頭部+載荷+秘鑰完成碰撞檢測校驗token是否被篡改

drf-jwt插件

官網

https://github.com/jpadilla/django-rest-framework-jwt

安裝

pip install djangorestframework-jwt

登錄-簽發token(生成token):urls.py   

# ObtainJSONWebToken視圖類就是通過username和password得到user對象然后簽發token(生成token)
from rest_framework_jwt.views import ObtainJSONWebToken, obtain_jwt_token
urlpatterns = [
    # url(r'^jogin/$', ObtainJSONWebToken.as_view()),
    url(r'^jogin/$', obtain_jwt_token),
]

認證-校驗token(解析token):全局或者配置drf-jwt的認證類  JSONWebTokenAuthentication

from rest_framework.views import APIView
from utils.response import APIResponse
# 必須登錄后才能訪問 - 通過了認證權限組件
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
class UserDetail(APIView):
    authentication_classes = [JSONWebTokenAuthentication]  # jwt-token校驗request.user
    permission_classes = [IsAuthenticated]  # 結合權限組件篩選掉游客
    def get(self, request, *args, **kwargs):
        return APIResponse(results={'username': request.user.username})

路由與接口測試

# 路由
url(r'^user/detail/$', views.UserDetail.as_view()),

# 接口:/api/user/detail/
# 認證信息:必須在請求頭的 Authorization 中攜帶 "jwt 后台簽發的token" 格式的認證字符串

注意:

1.簽發token的時候,只有post請求,沒有get請求
2.生成token的時候需要通過json傳入username和password
3.解析token的時候,get請求需要在Headers中傳入參數
Authorization    jwt 用戶對應的token值

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM