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'
    ],
相关推荐
快乐非自愿1 小时前
2026年Django生态现代化组件深度解析与实践
数据库·django·sqlite
㱘郳1 小时前
Python开发 Django和DRF框架 推荐部分B站视频
开发语言·python·django
ding_zhikai1 小时前
【Web应用开发笔记】Django笔记8:用户账户相关功能
笔记·后端·python·django
Mr数据杨1 小时前
【Dv3Admin】Django动态配置首页仪表盘
python·django·sqlite
程序设计实验室6 天前
分享一些2026年有意思的现代化Django生态组件
django
程序设计实验室7 天前
当人人都能用 AI 写代码时,我为什么选择重回 Django?
django·djangostarter
markfeng812 天前
Python+Django+H5+MySQL项目搭建
python·django
QQ40220549613 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
百锦再13 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
starlaky13 天前
Django入门笔记
笔记·django