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'
    ],
相关推荐
鸡鸭扣8 小时前
DRF/Django+Vue项目线上部署:腾讯云+Centos7.6(github的SSH认证)
前端·vue.js·python·django·腾讯云·drf
大叔_爱编程13 小时前
p020基于Django的4S店客户管理系统
vue.js·python·django·毕业设计·源码·课程设计·4s店客户管理系统
编程自留地1 天前
第11次:用户注册(完整版)
python·django·商城
Adolf_19931 天前
django的权限角色管理(RBAC)
数据库·python·django
是梦终空3 天前
Python毕业设计219—基于python+Django+vue的房屋租赁系统(源代码+数据库+万字论文)
python·django·vue·毕业设计·毕业论文·源代码·房屋租赁系统
Q_Q19632884753 天前
python小区物业管理系统-小区物业报修系统
开发语言·spring boot·python·django·flask·node.js·php
万能程序员-传康Kk3 天前
中国邮政物流管理系统(Django+mysql)
python·mysql·django
RunsenLIu3 天前
基于Django和Bootstrap开发的美食推荐系统
django·bootstrap·美食
RunsenLIu3 天前
基于Django实现的篮球论坛管理系统
后端·python·django