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'
    ],
相关推荐
沛沛老爹10 天前
Python Django全功能框架开发秘籍
python·django·orm·web开发·模板引擎·项目部署·表单处理
Q_Q196328847510 天前
python基于微信小程序的广西文化传承系统
开发语言·spring boot·python·微信小程序·django·flask
程序员爱钓鱼10 天前
Go Web开发框架实践:模板渲染与静态资源服务
后端·django·go
Q_Q196328847511 天前
python高校教务管理系统
开发语言·spring boot·python·django·flask·node.js·php
里探11 天前
Django中为api自定义一些装饰器:如参数校验等
python·django·装饰器模式
猫头虎12 天前
2025最新Python 100个常用函数在线体验项目
android·java·python·pycharm·django·pandas·pip
Q_Q51100828512 天前
python的校园兼职系统
开发语言·spring boot·python·django·flask·node.js·php
编程自留地12 天前
第14次:商品列表、热销商品及详情
python·django·商城
坤岭12 天前
Django项目搭建
django
noravinsc12 天前
django调用 paramiko powershell 获取cpu 个数
python·django·sqlite