Three certified frequency certification, JWT certification

A frequency source category

Dispath in Method 1. APIView self.initial (Request, * args, ** kwargs) points into
 2. self.check_throttles (Request)   # frequency verification 


# frequency components of the core source code analysis 
DEF check_throttles (Self, Request): 
    throttle_durations = []
     # 1. traversing frequency based authentication configuration, frequencies authentication initialization obtain a class object (class calls the authentication frequency __init __ () method) 
    # 2. frequency class object call allow_request authentication method is determined whether time limit ( no time limit accessibility, limited time inaccessible) 
    # 3. frequency certification class object again after limited time, call the wait method to get need to wait long for the next period of time can access 
    # frequency certification classes are derived SimpleRateThrottles class 
    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:
                 durations=[
                duration for duration in throttle_durations
                if duration is not None]
            duration = max(durations, default=None)
            self.throttled(request, duration)

 

Frequency custom classes:

1 . Frequency class inheritance Custom SimpleRateThrottle a class
 2 Set a scope type attribute, attribute value meaning any known views name string
 3. settings in the configuration file, the configuration DEFAULT_THROTTLE_RATES drf the format string {scope: ' number of times / time ' }
 4 . class in a custom frequency override get_cache_key method
     # objects returned limitations, and limitations related information string 
    # object does not limit the return None (only back None, is False or not ''Wait)

  SMS Interface 1 / min frequency limit

  Frequency: api / throttles.py

from rest_framework.throttling Import SimpleRateThrottle 

class SMSRateThrottle (SimpleRateThrottle): 
    scope = ' the SMS ' 

    # only method to get the phone number of the submitted limit 
    DEF get_cache_key (Self, Request, View): 
        Mobile = request.query_params.get ( ' Mobile ' )
         # no phone number, do not do a frequency limiting 
        IF  not Mobile:
             return None
         # returns can dynamically change the phone number, and difficult to duplicate strings, as an operation cache Key 
        return  ' Throttle _% (scope) S _% (ident) S ' % { ' scope': self.scope, 'ident': mobile}

  Configuration: settings.py

drf configuration 


REST_FRAMEWORK = {
          # frequency limits configuration 
          ' DEFAULT_THROTTLE_RATES ' : {
                   ' SMS ' : ' . 1 / min ' }, 
}

  View; views.py

from throttles. Import SMSRateThrottle 

class TestSMSAPIView (APIView):
     # partially disposed frequency authentication 
    throttle_classes = [SMSRateThrottle]
     DEF GET (Self, Request, * args, ** kwargs):
         return APIResponse (0, ' GET Get codes ' )
     DEF POST (Self, Request, * args, ** kwargs):
         return APIResponse (0, ' POST codes Get ' )

  Routing: api / url.py

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

  Restrictions interfaces

Only on / api / sms /? Mobile = specific phone number interfaces will have a frequency limit

 1. api / sms / or other interface to send unlimited
 2. The packet submitted api mobile / the SMS interfaces Unlimited
 3. not mobile (such as phone) submitted by field telephone interface unlimited

 

Figure certification rules

 

drf classification

 

Certification Rules evolution chart

  Database session Certification: inefficient

Cache Authentication: Efficient

 

jwt Certification: Efficient

Cache Authentication: Not easily complicated

jwt Certification: easily complicated

jwt certification

  advantage:

1 ) Do not store server token, token to each client's own storage, server stress small
 2 ) server and storage is the issue of verification token two algorithms, high efficiency certification issued
 3) algorithm to complete each cluster server low cost synchronization , routing completion of the project cluster deployment (to adapt to high concurrency)

  format:

1) jwt token采用三段式:头部.载荷.签名
2)每一部分都是一个json字典加密形参的字符串
3)头部和载荷采用的是base64可逆加密(前台后台都可以解密)
4)签名采用hash256不可逆加密(后台校验采用碰撞校验)
5)各部分字典的内容:
    头部:基础信息 - 公司信息、项目组信息、可逆加密采用的算法
    载荷:有用但非私密的信息 - 用户可公开信息、过期时间
    签名:头部+载荷+秘钥 不可逆加密后的结果
    注:服务器jwt签名加密秘钥一定不能泄露
    
签发token:固定的头部信息加密.当前的登陆用户与过期时间加密.头部+载荷+秘钥生成不可逆加密
校验token:头部可校验也可以不校验,载荷校验出用户与过期时间,头部+载荷+秘钥完成碰撞检测校验token是否被篡改

 

drf_jwt插件

  官网

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

  安装

>: pip3 install djangorestframework-jwt

  登录- 签发token: api/urls.py

# ObtainJSONWebToken视图类就是通过username和password得到user对象然后签发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: 全局或局部配置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" 格式的认证字符串

 

Guess you like

Origin www.cnblogs.com/panshao51km-cn/p/11723686.html