![22c454093abb00830950a53dac6b25f4.png](https://i-blog.csdnimg.cn/blog_migrate/b79a3f400ef0cf2ea88efe01409de75f.jpeg)
自己实现基于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](https://i-blog.csdnimg.cn/blog_migrate/5054ff3c34700638fbad8a3f08905701.jpeg)
# token =request.META.get('HTTP_Authorization'.upper()) # token放到请求体中
![6f5b8aa24cd0168960b6b96f04296b0f.png](https://i-blog.csdnimg.cn/blog_migrate/f3d470d84b95e0c80e187db1e3cd88e8.jpeg)