Django REST Framework JWT Auth TOKEN

TOKEN

项目文件树形图

在这里插入图片描述

配置

#1 settings.py

INSTALLED_APPS = [
    ...
    'app', # app
    'rest_framework', # 使用Django restframework
    'rest_framework.authtoken', #TOKEN 验证
]

...
AUTH_USER_MODEL = 'app.UserProfile' # 因为models使用AbstractUser
import datetime
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),# token的有效期
    'JWT_ISSUER': 'http://fasfdas.baicu',
    'JWT_AUTH_HEADER_PREFIX': 'TOKEN',
    'JWT_ALLOW_REFRESH': True,
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=1)
}
...

#2 models.py

from django.db import models
from django.contrib.auth.models import AbstractUser
class UserProfile(AbstractUser):
    age = models.IntegerField(verbose_name="年龄",default="1")

#3 views.py

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from app import models
from django.contrib.auth import login
from rest_framework_jwt.settings import api_settings
from django.contrib.auth import authenticate
from django.shortcuts import Http404
from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet
from rest_framework import serializers
from drf_dynamic_fields import DynamicFieldsMixin
from rest_framework import permissions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication


"""1. 登陆"""
class loginView(APIView):
    """登陆成功后,获取TOKEN"""
    def post(self,request):
        user = authenticate(username=request.data["username"], password=request.data["password"])
        if not user:
            raise Http404("账号密码不匹配")
        login(request, user)
        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)
        return Response({ "success": True, "msg": "登录成功","results": token},status=status.HTTP_200_OK)


"""2. 新增玩家"""
class UserSerializer(DynamicFieldsMixin,serializers.ModelSerializer):
    class Meta:
        model = models.UserProfile
        fields = ["username","password",]
    def create(self, validated_data):
        user= models.UserProfile.objects.create_user(**validated_data) # 这里新增玩家必须用create_user,否则密码不是秘文
        return user

class createUser(mixins.CreateModelMixin,GenericViewSet):
    queryset = models.UserProfile.objects.all()
    serializer_class = UserSerializer


"""3. 获取用户列表(验证token)"""
class getUser(mixins.ListModelMixin,GenericViewSet):
    authentication_classes = (JSONWebTokenAuthentication,)
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    queryset = models.UserProfile.objects.all()
    serializer_class = UserSerializer

#4 urls.py

from django.contrib import admin
from django.urls import path,include
from app import views
from rest_framework import routers
from app import views
createUserViewRouter = routers.DefaultRouter() # 新增用户
createUserViewRouter.register('', views.createUser,)
getUserRouter = routers.DefaultRouter() # 查看用户列表
getUserRouter.register('', views.getUser,)
urlpatterns = [
    path('admin/', admin.site.urls),
    path('gettoken/',views.loginView.as_view()), # 获取 token
    path('createuser/',include(createUserViewRouter.urls)), # 新增用户
    path('getuser/',include(getUserRouter.urls)), # 新增用户
]

获取TOKEN

创建一个用户(调用新增用户接口)

http://127.0.0.1:8000/createuser/

在这里插入图片描述

登陆用户,获取token

http://127.0.0.1:8000/gettoken/

在这里插入图片描述

验证token

未加token验证
class getUser(mixins.ListModelMixin,GenericViewSet):
    queryset = models.UserProfile.objects.all()
    serializer_class = UserSerializer
http://127.0.0.1:8000/getuser/

在这里插入图片描述

加token验证
class getUser(mixins.ListModelMixin,GenericViewSet):
    authentication_classes = (JSONWebTokenAuthentication,) # 验证token
    permission_classes = (permissions.IsAuthenticated,) # 只允许登陆成功的用户访问
    queryset = models.UserProfile.objects.all()
    serializer_class = UserSerializer
http://127.0.0.1:8000/getuser/

在这里插入图片描述

权限

permission_classes = (permissions.AllowAny,) # 所有用户
permission_classes = (permissions.IsAuthenticated,) # 登陆成功的token
permission_classes = (permissions.IsAuthenticatedOrReadOnly,) # 登陆成功的token,只能读操作
permission_classes = (permissions.IsAdminUser,) # 登陆成功的管理员token

Github

https://github.com/Coxhuang/TOKEN.git

官方文档

http://getblimp.github.io/django-rest-framework-jwt/

新的文档地址:

http://jpadilla.github.io/django-rest-framework-jwt/

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值