jwt簡單例子
一、登陸設置
1.不需要寫login的視圖類,使用jwt內置的。
2.需要前置條件,已有繼承AbstractUser models,并且有數據,用于校驗,返回token。
urls.py
from rest_framework_jwt.views import obtain_jwt_tokenurlpatterns = [path('login/', obtain_jwt_token),...
]
?二、訪問視圖類設置
需要兩者搭配,才能校驗
authentication_classes = [JSONWebTokenAuthentication,]# 權限控制permission_classes = [IsAuthenticated,]
urls.py
urlpatterns = [path('login/', obtain_jwt_token),path('orderview/', views.OrderAPIView.as_view()),path('userinfo/', views.UserInfoAPIView.as_view()),]
views.py
from rest_framework.views import APIView
from rest_framework.response import Response# 使用jwt 提供的認證類,局部使用
from rest_framework_jwt.authentication import JSONWebTokenAuthentication# 內置權限類
from rest_framework.permissions import IsAuthenticated# 但設定權限,登陸才能訪問。
class OrderAPIView(APIView):authentication_classes = [JSONWebTokenAuthentication,]# 權限控制permission_classes = [IsAuthenticated,]def get(self,request):return Response('這是訂單信息')class UserInfoAPIView(APIView):authentication_classes = [JSONWebTokenAuthentication,] # 可以理解成,全局設定了,游客可以訪問。def get(self,request):return Response('這是UserInfoAPIView')
自定制基于jwt認證類
一、控制接口返回的數據格式
utils.py
def My_jwt_response_payload_handler(token, user=None, request=None):return {'token': token,'msg':'登錄成功','status':100,'username':user.username}
settings.py
JWT_AUTH={'JWT_RESPONSE_PAYLOAD_HANDLER':'app02.utils.My_jwt_response_payload_handler'
}
二、自定義基于jwt的權限類
因為是自己定制的,所以可以返回錯誤信息,當沒有攜帶token字段。這是與上面“jwt簡單例子”的區別。
1.自定義驗證。
utils.py
from rest_framework_jwt.authentication import BaseAuthentication
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication
from rest_framework.exceptions import AuthenticationFailed
# from rest_framework_jwt.authentication import jwt_decode_handler
from rest_framework_jwt.utils import jwt_decode_handler # 與上面是一個
import jwt
from api import models# class MyJwtAuthentication(BaseAuthentication):
# def authenticate(self, request):
# jwt_value = request.META.get('HTTP_AUTHORIZATION')
# if jwt_value:
# try:
# # jwt 提供了通過三段token,取出payload的方法,并且有校驗功能
# payload = jwt_decode_handler(jwt_value)
#
# except jwt.ExpiredSignature:
# raise AuthenticationFailed('簽名過期')
# except jwt.InvalidTokenError:
# raise AuthenticationFailed('用戶非法')
# except Exception as e:
# raise AuthenticationFailed(str(e))
#
# # 因為payload 就是用戶信息字典
# print(payload)
# # 第一種,去數據庫查
# # user=models.User.objects.get(pk=payload.get('user_id'))
# # 第二種,不查數據庫
# user=models.User(id=payload.get('user_id'),username=payload.get('username'))
# return user,jwt_value
# # 沒有值,直接拋異常
# raise AuthenticationFailed('沒有攜帶認證信息')# 基于BaseJSONWebTokenAuthentication
# 可以使用內置方法獲取user
class MyJwtAuthentication(BaseJSONWebTokenAuthentication):def authenticate(self, request):jwt_value = request.META.get('HTTP_AUTHORIZATION')if jwt_value:try:# jwt 提供了通過三段token,取出payload的方法,并且有校驗功能payload = jwt_decode_handler(jwt_value)except jwt.ExpiredSignature:raise AuthenticationFailed('簽名過期')except jwt.InvalidTokenError:raise AuthenticationFailed('用戶非法')except Exception as e:raise AuthenticationFailed(str(e))# 因為payload 就是用戶信息字典user=self.authenticate_credentials(payload)return user,jwt_value# 沒有值,直接拋異常raise AuthenticationFailed('沒有攜帶認證信息')
2.視圖類
#
from app02.utils import MyJwtAuthentication
class GoodsInfoAPIView(APIView):authentication_classes = [MyJwtAuthentication,]def get(self,request,*args,**kwargs):print(request.user)return Response('商品信息')
3.urls.py
path('goods/', views.GoodsInfoAPIView.as_view()),