JWT安裝配置與使用


1.JWT安裝配置


 

1.1 安裝JWT

pip install djangorestframework-jwt==1.11.0

 1.2 syl/settings.py 配置jwt載荷中的有效期設置

# jwt載荷中的有效期設置
JWT_AUTH = {
    # 1.token前綴:headers中 Authorization 值的前綴
    'JWT_AUTH_HEADER_PREFIX': 'JWT',
    # 2.token有效期:一天有效
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
    # 3.刷新token:允許使用舊的token換新token
    'JWT_ALLOW_REFRESH': True,
    # 4.token有效期:token在24小時內過期, 可續期token
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(hours=24),
    # 5.自定義JWT載荷信息:自定義返回格式,需要手工創建
    'JWT_RESPONSE_PAYLOAD_HANDLER': 'user.utils.jwt_response_payload_handler',
}
jwt載荷中的有效期設置

 1.3 syl/settings.py JWT結合DRF進行認證權限配置

 

# 在DRF配置文件中開啟認證和權限 REST_FRAMEWORK = {   ...   # 用戶登陸認證方式   'DEFAULT_AUTHENTICATION_CLASSES': [     'rest_framework_jwt.authentication.JSONWebTokenAuthentication', # 在DRF中配置JWT認證     # 'rest_framework.authentication.SessionAuthentication', # 使用session時的認證器     # 'rest_framework.authentication.BasicAuthentication' # 提交表單時的認證器   ],   # 權限配置, 順序靠上的嚴格   'DEFAULT_PERMISSION_CLASSES': [   # 'rest_framework.permissions.IsAdminUser', # 管理員可以訪問   'rest_framework.permissions.IsAuthenticated', # 全局配置只有認證用戶可以訪問接口   # 'rest_framework.permissions.IsAuthenticatedOrReadOnly', # 認證用戶可以訪問, 否則只能讀取   # 'rest_framework.permissions.AllowAny', # 所有用戶都可以訪問   ], ... }

 

 

1.4 user/urls.py 增加獲取token接口和刷新token接口 

 

# -*- coding: utf-8 -*-
from django.urls import path, include
from user import views
from rest_framework.routers import SimpleRouter, DefaultRouter
from rest_framework.authtoken.views import obtain_auth_token
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token

# 自動生成路由方法, 必須使用視圖集
# router = SimpleRouter() # 沒有根路由 /user/ 無法識別
router = DefaultRouter()  # 1. 有根路由
router.register(r'user', views.UserViewSet)  # 2. 配置路由
urlpatterns = [
    path('index/', views.index),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),  # 認證地址

    path('login/', obtain_jwt_token),  # 獲取token,登錄視圖
    path('refresh/', refresh_jwt_token),  # 刷新token

    path('apiview/', views.UserInfoViewSet.as_view()),

]

urlpatterns += router.urls  # 3. 模塊地址
rest_framework_jwt

 

 

 

1.5 在user/utils.py中從寫jwt_response_payload_handler

 

# -*- coding: utf-8 -*-
def jwt_response_payload_handler(token, user=None, request=None, role=None):

    """
  自定義jwt認證成功返回數據
  :token 返回的jwt
  :user 當前登錄的用戶信息[對象]
  :request 當前本次客戶端提交過來的數據
  :role 角色
    """
    if user.first_name:
        name = user.first_name
    else:
        name = user.username
    return {
        'authenticated': 'true',
        'id': user.id,
        "role": role,
        'name': name,
        'username': user.username,
        'email': user.email,
        'token': token,
    }
jwt_response_payload_handler

 2.postman測試接口

 2.1 測試登錄接口,獲取token

 

http://192.168.56.100:8888/user/login/

 

 

 

 

 

'''自定義認證和權限優先級更高,可以覆蓋settings.py中的 '''
# 自定義權限類
permission_classes = (MyPermission,) # 自定義認證類, 自定義會覆蓋全局配置
authentication_classes = (JSONWebTokenAuthentication,)

 

 2.2 使用獲得的token獲取所有用戶信息

 

http://192.168.56.100:8888/user/login/ 

 

 

 

 3.源碼分析

class JSONWebTokenAPIView(APIView):   """   Base API View that various JWT interactions inherit from.   """   permission_classes = ()   authentication_classes = ()
  
def get_serializer_context(self):     """     Extra context provided to the serializer class.     """     return {       'request': self.request,       'view': self,     }   def get_serializer_class(self):     """     Return the class to use for the serializer.     Defaults to using `self.serializer_class`.     You may want to override this if you need to provide different     serializations depending on the incoming request.     (Eg. admins get full serialization, others get basic serialization)     """     assert self.serializer_class is not None, (       "'%s' should either include a `serializer_class` attribute, "       "or override the `get_serializer_class()` method."       % self.__class__.__name__)     return self.serializer_class   def get_serializer(self, *args, **kwargs):     """     Return the serializer instance that should be used for validating and     deserializing input, and for serializing output.     """     serializer_class = self.get_serializer_class()     kwargs['context'] = self.get_serializer_context()     return serializer_class(*args, **kwargs)   def post(self, request, *args, **kwargs):     serializer = self.get_serializer(data=request.data)     if serializer.is_valid():       user = serializer.object.get('user') or request.user # User表對象       token = serializer.object.get('token') # 獲取到生成的token       response_data = jwt_response_payload_handler(token, user, request)       response = Response(response_data)        if api_settings.JWT_AUTH_COOKIE:         expiration = (datetime.utcnow() +           api_settings.JWT_EXPIRATION_DELTA)         response.set_cookie(api_settings.JWT_AUTH_COOKIE,                     token,                     expires=expiration,                     httponly=True)       return response    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

 

 

1.編寫注冊接口

1.1 user/urls.py 中添加路由

 

urlpatterns = [ path('register/', views.RegisterView.as_view()), # 注冊視圖, /user/register/
]

 

 1.2 user/views.py 中寫注冊視圖函數

class RegisterView(APIView): """ 用戶注冊, 權限是: 匿名用戶可訪問 """
    # 自定義權限類
    permission_classes = (AllowAny,) def post(self, request): """ 接收郵箱和密碼, 前端校驗兩遍一致性, 注冊成功后返回成功, 然 后用戶自行登錄獲取token 1. 隨機用戶名 2. 生成用戶 3. 設置用戶密碼 4. 保存用戶 :param request: :return: {'code':0,'msg':'注冊成功'} """ email = request.data.get('email') passwrod = request.data.get('password') if all([email, passwrod]): pass
        else: return Response({'code':9999,'msg':'參數不全'}) rand_name = self.randomUsername() user = User(username=rand_name, email=email) user.set_password(passwrod) user.save() return Response({'code': 0, 'msg': '注冊成功'}) def randomUsername(self): """ 生成隨機用戶名: 格式: SYL + 年月日時分 + 5位隨機數 :return: """ d = datetime.datetime.now() base = 'SYL' time_str = '%04d%02d%02d%02d%02d'  %(d.year,d.month, d.day, d.hour,d.minute) rand_num = str(random.randint(10000, 99999) return base + time_str + rand_num 

 

 2.重寫django認證

2.1 syl/settings.py 中指定自定義后端認證函數位置

# 自定義驗證后端
AUTHENTICATION_BACKENDS = ['user.utils.EmailAuthBackend']

2.2 user/utils.py 中重寫認證函數

# 以前使用username進行用戶驗證,現在修改成email進行驗證
class EmailAuthBackend:
    def authenticate(self, request, username=None, password=None):
        try:
            user = User.objects.get(username=username)
        except Exception as e:
            print(e)
            user = None
        if not user:
            try:
                user = User.objects.get(email=username)
            except Exception as e:
                print(e)
                user = None
        if user and user.check_password(password):
            return user
        else:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None
EmailAuthBackend

 

 

 

 

 

3.注冊用戶 & 測試登錄

3.1 注冊接口測試

http://192.168.56.100:8888/user/register/

 

 

 3.2 登錄接口測試

注: 認證時只能識別username,所以必須要在請求中攜帶username字段

http://192.168.56.100:8888/user/login/

 

 

 3.3 獲取用戶列表接口測試

  · 訪問接口

http://192.168.56.100:8888/user/user/5/

 

  · 測試自定義權限

# 自定義權限類
permission_classes = (MyPermission,) # 自定義認證類, 自定義會覆蓋全局配置
authentication_classes = (JSONWebTokenAuthentication,)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM