Django中使用JWT

JWT

"""
一、組成: 
header.payload.signature 頭.載荷.簽名

二、距離:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6Im93ZW4iLCJleHAiOjE1NTgzMDM1NDR9.4j5QypLwufjpqoScwUB9LYiuhYcTw1y4dPrvnv7DUyo

3:介紹:
header:通常存放如何處理token的方式:加密的算法、是否有簽名等
payload:數據的主體部分:用戶信息、發行者、過時時間等
signature:簽名:將header、payload再結合密碼鹽總體處理一下
"""

工做原理

"""
1) jwt = base64(頭部).base64(載荷).hash256(base64(頭部).base(載荷).密鑰)
2) base64是可逆的算法、hash256是不可逆的算法
3) 密鑰是固定的字符串,保存在服務器
"""

drf-jwt

官網
https://github.com/jpadilla/django-rest-framework-jwt
安裝子:虛擬環境
pip install djangorestframework-jwt
使用:user/urls.py
from django.urls import path
from rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
    path('login/', obtain_jwt_token),
]
測試接口:post請求
"""
postman發生post請求

接口:http://api.luffy.cn:8000/user/login/

數據:
{
    "username":"admin",
    "password":"admin"
}
"""

drf-jwt開發

配置信息:JWT_AUTH到dev.py中
import datetime
JWT_AUTH = {
    # 過時時間
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
    # 自定義認證結果:見下方序列化user和自定義response
    'JWT_RESPONSE_PAYLOAD_HANDLER': 'user.utils.jwt_response_payload_handler',  
}
序列化user:user/serializers.py(本身建立)
from rest_framework import serializers
from .models import User
class UserModelSerializer(serializers.ModelSerializer):
    """輪播圖序列化器"""
    class Meta:
        model = User
        fields = ["username", "mobile"]
自定義response:user/utils.py
from .serializers import UserModelSerializers
def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'user': UserModelSerializer(user).data
    }
    # restful 規範
    # return {
    #     'status': 0,
    #     'msg': 'OK',
    #     'data': {
    #         'token': token,
    #         'username': user.username
    #     }
    # }
基於drf-jwt的全局認證:user/authentications.py(本身建立)
import jwt
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_jwt.authentication import jwt_decode_handler
from rest_framework_jwt.authentication import get_authorization_header
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication
class JSONWebTokenAuthentication(BaseJSONWebTokenAuthentication):
        def authenticate(self, request):
            # 採用drf獲取token的手段 - HTTP_AUTHORIZATION - Authorization
            token = get_authorization_header(request)
            if not token:
                raise AuthenticationFailed('Authorization 字段是必須的')
            # 能夠添加反扒措施:原功能是token有前綴

            # drf-jwt認證校驗算法
            try:
                payload = jwt_decode_handler(token)
            except jwt.ExpiredSignature:
                raise AuthenticationFailed('簽名過時')
            except jwt.InvalidTokenError:
                raise AuthenticationFailed('非法用戶')
            user = self.authenticate_credentials(payload)
            # 將認證結果丟該drf
            return user, token
全局啓用:settings/dev.py
REST_FRAMEWORK = {
    # 認證模塊
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'user.authentications.JSONWebTokenAuthentication',
    ),
}
局部啓用禁用:任何一個cbv類首行
# 局部禁用
authentication_classes = []

# 局部啓用
from user.authentications import JSONWebTokenAuthentication
authentication_classes = [JSONWebTokenAuthentication]
多方式登陸:user/utils.py
from django.contrib.auth.backends import ModelBackend
from .models import User
import re
class JWTModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        :param request:
        :param username: 前臺傳入的用戶名
        :param password: 前臺傳入的密碼
        :param kwargs:
        :return:
        """
        try:
            if re.match(r'^1[3-9]\d{9}$', username):
                user = User.objects.get(mobile=username)
            elif re.match(r'.*@.*', username):
                user = User.objects.get(email=username)
            else:
                user = User.objects.get(username=username)
        except User.DoesNotExist:
            return None  # 認證失敗就返回None便可,jwt就沒法刪除token
        # 用戶存在,密碼校驗經過,是活着的用戶 is_active字段爲1
        if user and user.check_password(password) and self.user_can_authenticate(user):
            return user  # 認證經過返回用戶,交給jwt生成token
配置多方式登陸:settings/dev.py
AUTHENTICATION_BACKENDS = ['user.utils.JWTModelBackend']
手動簽發JWT:瞭解 - 能夠擁有原生登陸基於Model類user對象簽發JWT
from rest_framework_jwt.settings import api_settings

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)


# 瞭解,原生視圖
# 原生APIView能夠實現手動簽發 jwt
class LoginAPIView(APIView):
    def post(self):
        # 完成手動簽發
        pass
相關文章
相關標籤/搜索