drf 使用jwt

安装jwt

复制代码
pip install pyJwt

添加登录url'

复制代码
    path("jwt/login",views.JwtLoginView.as_view(),name='jwt-login'),
    path("jwt/order",views.JwtOrderView.as_view(),name='jwt-order'),

创建视图

复制代码
from django.contrib.auth import authenticate

import jwt
from jwt import exceptions
import datetime



class JwtLoginView(APIView):
    def post(self,request,*args,**kwargs):
        username = request.data.get("username")
        password = request.data.get("password")
        user_object = authenticate(username=username, password=password)
        if not user_object:
            return Response(data={"msg": "没有此用户信息"}, status=status.HTTP_404_NOT_FOUND)

        headers = {
            'typ':'jwt',
            'alg':'HS256'
        }
        payload = {
            'user_id':user_object.id,
            'username':user_object.username,
            'exp':datetime.datetime.now()+datetime.timedelta(minutes=5)
        }
        token = jwt.encode(headers=headers,payload=payload,key=salt,algorithm="HS256").encode("utf-8")
        return Response(data=token, status=status.HTTP_200_OK)

class JwtOrderView(APIView):
    def get(self, request, *args, **kwargs):
        token = request.data.get("token")
        print(token)
        payload = None
        msg = None
        try:
            payload = jwt.decode(token,salt,algorithms='HS256')
        except exceptions.ExpiredSignatureError:
            msg = 'token已失效'
        except exceptions.DecodeError:
            msg = 'token认证失败'
        except exceptions.InvalidTokenError:
            msg = '非法的token'

        if not  payload:
            return  Response({'code':1003,'error':msg})

        return Response("list")

抽取登录、验证操作

生成token #course/utils/jwt_auth.py

复制代码
import jwt
import datetime
from django.conf import settings


def create_token(payload, timeout=1):
    salt = settings.SECRET_KEY
    headers = {
        'typ': 'jwt',
        'alg': 'HS256'
    }
    payload['exp'] = datetime.datetime.now() + datetime.timedelta(minutes=timeout)
    token = jwt.encode(headers=headers, payload=payload, key=salt, algorithm="HS256").encode("utf-8")
    return token

登录验证 #course/extensions/auth.py

复制代码
from rest_framework.authentication import BaseAuthentication
import jwt
from jwt import exceptions
import datetime
from rest_framework.exceptions import AuthenticationFailed
from django.conf import settings


class JwtAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.data.get("token")
        salt = settings.SECRET_KEY
        payload = None
        try:
            payload = jwt.decode(token, salt, algorithms='HS256')
        except exceptions.ExpiredSignatureError:

            raise AuthenticationFailed({'code': 1003, 'errors': 'token已失效'})
        except exceptions.DecodeError:

            raise AuthenticationFailed({'code': 1003, 'errors': 'token认证失败'})
        except exceptions.InvalidTokenError:
            raise AuthenticationFailed({'code': 1003, 'errors': '非法的token'})

        return (payload, token)

调用

复制代码
class ProLoginView(APIView):
    authentication_classes=[]
    def post(self,request,*args,**kwargs):
        username = request.data.get("username")
        password = request.data.get("password")
        user_object = authenticate(username=username, password=password)
        if not user_object:
            return Response(data={"msg": "没有此用户信息"}, status=status.HTTP_404_NOT_FOUND)
        token = create_token({'id':user_object.id,'name':user_object.username})
        return Response(data=token, status=status.HTTP_200_OK)

class ProOrderView(APIView):
    authentication_classes(JwtAuthentication)
    def get(self, request, *args, **kwargs):
        print(request.user)
        return Response("list")

修改setting.py

复制代码
 'DEFAULT_AUTHENTICATION_CLASSES':[
        # 'rest_framework.authentication.BasicAuthentication',#基本的用户名密码验证
        # 'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework.authentication.TokenAuthentication',
        'course.extensions.auth.JwtAuthentication'
    ],
相关推荐
blues_C1 天前
十三、【核心功能篇】测试计划管理:组织和编排测试用例
vue.js·django·测试用例·drf·测试平台
恸流失1 天前
DJango项目
后端·python·django
编程大全2 天前
41道Django高频题整理(附答案背诵版)
数据库·django·sqlite
网安小张2 天前
解锁FastAPI与MongoDB聚合管道的性能奥秘
数据库·python·django
KENYCHEN奉孝2 天前
Pandas和Django的示例Demo
python·django·pandas
老胖闲聊2 天前
Python Django完整教程与代码示例
数据库·python·django
noravinsc2 天前
django paramiko 跳转登录
后端·python·django
践行见远2 天前
django之请求处理过程分析
数据库·django·sqlite
声声codeGrandMaster2 天前
Django之表格上传
后端·python·django
菌菌的快乐生活2 天前
网站静态文件加速-Django项目静态文件存储到腾讯云COS存储提升网络请求速度
django·cos存储