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'
    ],
相关推荐
c8i15 小时前
drf初步梳理
python·django
c8i2 天前
django中的FBV 和 CBV
python·django
百锦再3 天前
[特殊字符] Python在CentOS系统执行深度指南
开发语言·python·plotly·django·centos·virtualenv·pygame
计算机编程小央姐3 天前
跟上大数据时代步伐:食物营养数据可视化分析系统技术前沿解析
大数据·hadoop·信息可视化·spark·django·课程设计·食物
诗句藏于尽头3 天前
Django模型与数据库表映射的两种方式
数据库·python·django
IT学长编程3 天前
计算机毕业设计 基于Hadoop豆瓣电影数据可视化分析设计与实现 Python 大数据毕业设计 Hadoop毕业设计选题【附源码+文档报告+安装调试
大数据·hadoop·python·django·毕业设计·毕业论文·豆瓣电影数据可视化分析
Python私教4 天前
Django全栈班v1.04 Python基础语法 20250912 下午
后端·python·django
凡梦千华4 天前
Django时区感知
后端·python·django
程序设计实验室4 天前
Django过时了吗?从ASGI到AI时代的思考
django
Python私教4 天前
Django全栈班v1.04 Python基础语法 20250912 上午
后端·python·django