drf-jwt

drf-jwt

官网
http://getblimp.github.io/django-rest-framework-jwt/
安装子:虚拟环境
pip install djangorestframework-jwt
使用:user/urls.py
from django.urls import path
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
    path('login/', obtain_jwt_token),
]
测试接口:post请求
"""
postman发生post请求

接口:http://api.luffy.cn:8000/user/login/

数据:
{
	"username":"admin",
	"password":"admin"
}
"""

自定义jwt登录(手动签发jwt)

1、View.py中定义一个类

from rest_framework.views import APIView
from rest_framework_jwt.serializers import jwt_payload_handler
from rest_framework_jwt.serializers import jwt_encode_handler
from django.contrib import auth
class LoginAPIView(APIView):
    def post(self,request,*args,**kwargs):
        username = request.data.get('username')
        password = request.data.get('password')
        if not (username and password):
            return Response({
                'error':'用户名或密码不能为空'
            })
        user_obj = auth.authenticate(username=username,password=password,is_active=True)
        if user_obj:
            payload = jwt_payload_handler(user_obj)
            token = jwt_encode_handler(payload)
            return Response({
                'status':0,
                'msg':'ok',
                'token':token
            })
        else:
            return Response({
                'status':1,
                'msg':'用户名或密码错误'
            })

2、serializers.py中定义基于auth_user的序列化与反序列化的类

class LoginModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.User
        fields = ('username', 'password')
        extra_kwargs = {
            'password':{
                'write_only':True
            }
        }

3、url中设置指向路由

from api import views
url(r'^login/$', views.LoginAPIView.as_view()),

jwt过期时间

在setting中配置
import datetime
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),
}

authentication_classes和permission_classes

两者配合使用可省略session

# 必须完成jwt校验才能得到登陆状态
    # authentication_classes = [JSONWebTokenAuthentication]
    authentication_classes = [JWTAuthentication]
    # 登陆后才能查看
    permission_classes = [IsAuthenticated]

基于drf-jwt的全局认证:user/authentications.py(自己创建)

import jwt
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_jwt.authentication import jwt_decode_handler
from rest_framework_jwt.authentication import get_authorization_header
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication

class JSONWebTokenAuthentication(BaseJSONWebTokenAuthentication):
    def authenticate(self, request):
        jwt_value = get_authorization_header(request)

        if not jwt_value:
            raise AuthenticationFailed('Authorization 字段是必须的')
        try:
            payload = jwt_decode_handler(jwt_value)
        except jwt.ExpiredSignature:
            raise AuthenticationFailed('签名过期')
        except jwt.InvalidTokenError:
            raise AuthenticationFailed('非法用户')
        user = self.authenticate_credentials(payload)

        return user, jwt_value

全局启用:settings/dev.py

REST_FRAMEWORK = {
    # 认证模块
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'user.authentications.JSONWebTokenAuthentication',
    ),
}

局部启用禁用:任何一个cbv类首行

# 局部禁用
authentication_classes = []

# 局部启用
from user.authentications import JSONWebTokenAuthentication
authentication_classes = [JSONWebTokenAuthentication]

自定义频率认证类

方法一设置scope

1setting中配置
REST_FRAMEWORK = {
# 自定义频率类
'DEFAULT_THROTTLE_CLASSES': [],
'DEFAULT_THROTTLE_RATES': {
#'user': '3/min',
#'anon': '3/min',
'time_scope': '3/min',
'time_rate': '3/min',
},
}
2自定义认证类中.py中

from rest_framework.throttling import SimpleRateThrottle
class MyRateThrottle(SimpleRateThrottle):
    scope = 'time_scope'
    def get_cache_key(self, request, view):
        return 'throttle_time_scope'

3在View需要限制访问的类中

from . import throttles
# 自定义频率控制
# throttle_classes = [MyRateThrottle]
# throttle_classes = [throttles.TimeRateThrottle]

第二种设置rate

1自定义认证类中.py中

class TimeRateThrottle(SimpleRateThrottle):
     rate = '3/min'
     def get_cache_key(self, request, view):
         return 'throttle_time_rate'

2在View需要限制访问的类中

from . import throttles
# 自定义频率控制
# throttle_classes = [MyRateThrottle]
# throttle_classes = [throttles.TimeRateThrottle]

系统默认频率控制

1、setting中
REST_FRAMEWORK = {
# 自定义频率类
'DEFAULT_THROTTLE_CLASSES': [],
'DEFAULT_THROTTLE_RATES': {
'user': '3/min',
'anon': '3/min',
},
}
2、在View需要限制访问的类中

1from rest_framework import throttling
2authentication_classes = [JWTAuthentication]
3# 系统频率控制
    # throttle_classes = [throttling.AnonRateThrottle]  # 只限制游客
    # throttle_classes = [throttling.UserRateThrottle]  # 登陆用户通过用户pk限制,游客通过ip限制

原文地址:https://www.cnblogs.com/huanghongzheng/p/11385958.html