自定义request_Django-drf-自定义基于JWT的认证类

22c454093abb00830950a53dac6b25f4.png

自己实现基于jwt的认证类,通过认证,才能继续访问,通不过认证就返回错误

写一个自定义的认证类

token=request.GET.get('token') # token放到请求地址中

from rest_framework_jwt.utils import jwt_decode_handler
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication

class JwtAuthentication(BaseJSONWebTokenAuthentication):
    def authenticate(self, request):
        # 认证逻辑()
        # token信息可以放在请求头中,请求地址中
        # key值可以随意叫
        token=request.GET.get('token')  # token放到请求地址中
        # token = request.META.get('HTTP_Authorization'.upper())  # token放到请求头中
        # 校验token是否合法
        try:
            payload = jwt_decode_handler(token)
        except jwt.ExpiredSignature:
            raise AuthenticationFailed('过期了')
        except jwt.DecodeError:
            raise AuthenticationFailed('解码错误')
        except jwt.InvalidTokenError:
            raise AuthenticationFailed('不合法的token')
        user = self.authenticate_credentials(payload)
        return (user, token)

在视图类中配置

from app01.auth import JwtAuthentication
class OrderView(APIView):

    authentication_classes = [JwtAuthentication, ]  # 配置自定义jwt认证类

    def get(self, request):
        print(request.user.username)
        return Response('订单的数据')

872b276b6a88b1644bb2ac046950809e.png

# token =request.META.get('HTTP_Authorization'.upper()) # token放到请求体中

6f5b8aa24cd0168960b6b96f04296b0f.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值