复习
"""
1、认证组件:校验认证字符串,得到request.user
没有认证字符串,直接放回None,游客
有认证字符串,但认证失败抛异常,非法用户
有认证字符串,且认证通过返回 用户,认证信息 元组,合法用户
用户存放到request.user | 认证信息存放到request.auth
自定义认证类
class MyAuthentication(BaseAuthentication):
def authenticate(self, request):
# 1)从request中拿auth字符串:return None | 继续
# 2)校验auth:抛异常 | (user, auth)
全局或局部配置
REST_FRAMEWORK = {
# 认证类配置
'DEFAULT_AUTHENTICATION_CLASSES': [
'自定义的认证类MyAuthentication',
],
}
class MyAPIView(APIView):
authentication_calsses = []
pass
2、权限组件:校验request.user是否拥有权限
有权限,返回True
无权限,返回False
自定义权限类:
class MyPermission(BasePermission):
def has_permission(self, request, view):
# 1)request.user或其他信息(请求方式)等判断:True | False
全局或局部配置
REST_FRAMEWORK = {
# 权限类配置
'DEFAULT_PERMISSION_CLASSES': [
'自定义的权限类MyPermission',
],
}
class MyAPIView(APIView):
permission_classes = []
pass
"""
频率类源码
入口
def check_throttles(self, request):
throttle_durations = []
for throttle in self.get_throttles():
if not throttle.allow_request(request, self):
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)
自定义频率类
短信接口 1/min 频率限制
频率:api/throttles.py
from rest_framework.throttling import SimpleRateThrottle
class SMSRateThrottle(SimpleRateThrottle):
scope = 'sms'
def get_cache_key(self, request, view):
mobile = request.query_params.get('mobile')
if not mobile:
return None
return 'throttle_%(scope)s_%(ident)s' % {'scope': self.scope, 'ident': mobile}
配置:settings.py
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')
路由:api/url.py
url(r'^sms/$', views.TestSMSAPIView.as_view()),
限制的接口
认证规则图
django不分离
drf分类
认证规则演变图
数据库session认证:低效
缓存认证:高效
jwt认证:高效
缓存认证:不易并发
jwt认证:易并发
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
安装
>: pip3 install djangorestframework-jwt
登录 - 签发token:api/urls.py
from rest_framework_jwt.views import ObtainJSONWebToken, obtain_jwt_token
urlpatterns = [
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]
permission_classes = [IsAuthenticated]
def get(self, request, *args, **kwargs):
return APIResponse(results={'username': request.user.username})
路由与接口测试
url(r'^user/detail/$', views.UserDetail.as_view()),