Django rest_framework_jwt
-- JWT (JSON WEB TOCKEN)
JWT通常由三部分组成: 头信息(header), 负载(payload)和签名(signature)
-- 这里不说太多概念,直接上码
-- 我这里的环境是 Django==2.0.4 Py3 djangorestframework-jwt==1.11.0
--这里直接跳过创建项目
INSTALLED_APPS = [ 'rest_framework.authtoken', ] ## 配置jwt 放在最下面就可以 """ 配置JWT 验证 """ REST_FRAMEWORK = { # 身份认证 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } ### 注意这俩个 -- app -- 就是你子应用的名字 import datetime JWT_AUTH = { 'JWT_AUTH_HEADER_PREFIX': 'JWT', 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1), 'JWT_RESPONSE_PAYLOAD_HANDLER': 'app.views.jwt_response_payload_handler', # 重新login登录返回函数 } AUTH_USER_MODEL='app.User' # 指定app 的User表
from django.contrib.auth.models import AbstractUser class User(AbstractUser): username = models.CharField(max_length=64, unique=True) password = models.CharField(max_length=255) phone = models.CharField(max_length=64) token = models.CharField(max_length=255)
from rest_framework_jwt.settings import api_settings from rest_framework import serializers from app.models import User class UserInfoSerializer(serializers.Serializer): username = serializers.CharField(min_length=3,max_length=20) # 显示普通字段 class Meta: model = User class UserSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() phone = serializers.CharField() token = serializers.CharField(read_only=True) def create(self, data): user = User.objects.create(**data) user.set_password(data.get('password')) user.save() # 补充生成记录登录状态的token jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) user.token = token return user
from app.models import User from rest_framework.views import APIView from rest_framework.views import Response from rest_framework.permissions import IsAuthenticated from rest_framework_jwt.authentication import JSONWebTokenAuthentication from app.serializers import UserSerializer class RegisterView(APIView): def post(self, request, *args, **kwargs): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) return Response(serializer.errors, status=400) # 重新用户登录返回函数 def jwt_response_payload_handler(token, user=None, request=None): ''' :param token: jwt生成的token值 :param user: User对象 :param request: 请求 ''' return { 'token': token, 'user': user.username, 'userid': user.id } # 测试必须携带token才能访问接口 class UserList(APIView): permission_classes = [IsAuthenticated] # 接口中加权限 authentication_classes = [JSONWebTokenAuthentication] def get(self,request, *args, **kwargs): print(request.META.get('HTTP_AUTHORIZATION', None)) return Response({'name':'tom'}) def post(self,request, *args, **kwargs): return Response({'name':'xiaomo'})
from app import views from rest_framework_jwt.views import obtain_jwt_token path('register/', views.RegisterView.as_view()), path('login/', obtain_jwt_token), # 用户登录后返回token path('list/', views.UserList.as_view()), # 测试需要携带token才能访问
完成。