drf框架 - JWT認證插件

JWT認證

JWT認證方式與其餘認證方式對比:

優勢

1) 服務器不要存儲token,token交給每個客戶端本身存儲,服務器壓力小
2)服務器存儲的是 簽發和校驗token 兩段算法,簽發認證的效率高
3)算法完成各集羣服務器同步成本低,路由項目完成集羣部署(適應高併發

格式

1) jwt token採用三段式:頭部.載荷.簽名 2)每一部分都是一個json字典加密形參的字符串
3)頭部和載荷採用的是base64可逆加密(前臺後臺均可以解密)
4)簽名採用hash256不可逆加密(後臺校驗採用碰撞校驗)
5)各部分字典的內容:
    頭部:基礎信息 - 公司信息、項目組信息、可逆加密採用的算法
    載荷:有用但非私密的信息 - 用戶可公開信息、過時時間
    簽名:頭部+載荷+祕鑰 不可逆加密後的結果
    注:服務器jwt簽名加密祕鑰必定不能泄露
    
簽發token:固定的頭部信息加密.當前的登錄用戶與過時時間加密.頭部+載荷+祕鑰生成不可逆加密
校驗token:頭部可校驗也能夠不校驗,載荷校驗出用戶與過時時間,頭部+載荷+祕鑰完成碰撞檢測校驗token是否被篡改

 

drf - jwt 插件

官網

https://github.com/jpadilla/django-rest-framework-jwt

 

安裝

>: pip3 install djangorestframework-jwt

 

token的簽發與校驗初識:

  • 登陸 - 簽發token:api/urls.py

# ObtainJSONWebToken視圖類就是經過username和password獲得user對象而後簽發token
from rest_framework_jwt.views import ObtainJSONWebToken, obtain_jwt_token
urlpatterns = [
    # url(r'^jogin/$', ObtainJSONWebToken.as_view()),
    url(r'^jogin/$', obtain_jwt_token),  # 登陸接口url
]

 

  • 認證 - 校驗token:全局或局部配置drf-jwt的認證類 JSONWebTokenAuthentication

from rest_framework.views import APIView
from utils.response import APIResponse
# 必須登陸後才能訪問 - 經過了認證權限組件
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication

class UserDetail(APIView): authentication_classes = [JSONWebTokenAuthentication] # jwt-token校驗request.user permission_classes = [IsAuthenticated] # 結合權限組件篩選掉遊客 def get(self, request, *args, **kwargs): return APIResponse(results={'username': request.user.username})

 

  • 路由與接口測試

# 路由
url(r'^user/detail/$', views.UserDetail.as_view()),
​
# 接口:/api/user/detail/
# 認證信息:必須在請求頭的 Authorization 中攜帶 "jwt 後臺簽發的token" 格式的認證字符串

 

簽發token

  • 源碼入口

# 前提:給一個局部禁用了全部 認證與權限 的視圖類發送用戶信息獲得token,其實就是登陸接口
# 1)rest_framework_jwt.views.ObtainJSONWebToken 的 父類 JSONWebTokenAPIView 的 post 方法
#       接受有username、password的post請求
# 2)post方法將請求數據交給 rest_framework_jwt.serializer.JSONWebTokenSerializer 處理
#       完成數據的校驗,會走序列化類的 全局鉤子校驗規則,校驗獲得登陸用戶並簽發token存儲在序列化對象中

 

  • 核心源碼:rest_framework_jwt.serializer.JSONWebTokenSerializer的validate(self, attrs)方法

def validate(self, attrs):
    # 帳號密碼字典
    credentials = {
        self.username_field: attrs.get(self.username_field),
        'password': attrs.get('password')
    }
    if all(credentials.values()):
        # 簽發token第1步:用帳號密碼獲得user對象
        user = authenticate(**credentials)
        if user:
            if not user.is_active:
                msg = _('User account is disabled.')
                raise serializers.ValidationError(msg)
            # 簽發token第2步:經過user獲得payload,payload包含着用戶信息與過時時間
            payload = jwt_payload_handler(user)
            # 在視圖類中,能夠經過 序列化對象.object.get('user'或者'token') 拿到user和token 
            return {
                # 簽發token第3步:經過payload簽發出token
                'token': jwt_encode_handler(payload),
                'user': user
            }
        else:
            msg = _('Unable to log in with provided credentials.')
            raise serializers.ValidationError(msg)
    else:
        msg = _('Must include "{username_field}" and "password".')
        msg = msg.format(username_field=self.username_field)
        raise serializers.ValidationError(msg)

 

  • 手動簽發token邏輯

1)經過username、password獲得user對象
2)經過user對象生成payload:jwt_payload_handler(user) => payload from rest_framework_jwt.serializers import jwt_payload_handler
3)經過payload簽發token:jwt_encode_handler(payload) => token from rest_framework_jwt.serializers import jwt_encode_handler

 

校驗token

  • 源碼入口

# 前提:訪問一個配置了jwt認證規則的視圖類,就須要提交認證字符串token,在認證類中完成token的校驗
# 1)rest_framework_jwt.authentication.JSONWebTokenAuthentication 的 父類 BaseJSONWebTokenAuthentication 的 authenticate 方法
#       請求頭拿認證信息jwt-token => 經過反爬小規則肯定有用的token => payload => user

 

  • 核心源碼:rest_framework_jwt.authentication.BaseJSONWebTokenAuthentication的authenticate(self, request)方法

def authenticate(self, request):
    # 帶有反爬小規則的獲取token:前臺必須按 "jwt token字符串" 方式提交
    # 校驗user第1步:從請求頭 HTTP_AUTHORIZATION 中拿token,並提取
    jwt_value = self.get_jwt_value(request)
    # 遊客
    if jwt_value is None:
        return None
    # 校驗
    try:
        # 校驗user第2步:token => payload
        payload = jwt_decode_handler(jwt_value)
    except jwt.ExpiredSignature:
        msg = _('Signature has expired.')
        raise exceptions.AuthenticationFailed(msg)
    except jwt.DecodeError:
        msg = _('Error decoding signature.')
        raise exceptions.AuthenticationFailed(msg)
    except jwt.InvalidTokenError:
        raise exceptions.AuthenticationFailed()
    # 校驗user第3步:token => payload
    user = self.authenticate_credentials(payload)
​
    return (user, jwt_value)

 

  • 手動校驗token邏輯

1)從請求頭中獲取token
2)根據token解析出payload:jwt_decode_handler(token) => payloay from rest_framework_jwt.authentication import jwt_decode_handler 3)根據payload解析出user:self.authenticate_credentials(payload) => user
      繼承drf-jwt的BaseJSONWebTokenAuthentication,拿到父級的authenticate_credentials方法

 

自定義drf-jwt配置

settings.py

# 自定義 drf-jwt 配置
import datetime
JWT_AUTH = {
    # user => payload
    'JWT_PAYLOAD_HANDLER':
        'rest_framework_jwt.utils.jwt_payload_handler',
    # payload => token
    'JWT_ENCODE_HANDLER':
        'rest_framework_jwt.utils.jwt_encode_handler',
    # token => payload
    'JWT_DECODE_HANDLER':
        'rest_framework_jwt.utils.jwt_decode_handler',
    # token過時時間
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),
    # token刷新的過時時間
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
    # 反爬小措施前綴
    'JWT_AUTH_HEADER_PREFIX': 'JWT',  # 默認token前要加上JWT,能夠修改爲其餘,也能夠手動建立校驗規則
}

 

案例:實現多方式登錄簽發token

  • models.py前端

from django.db import models
​
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
    mobile = models.CharField(max_length=11, unique=True)
​
    class Meta:
        db_table = 'api_user'
        verbose_name = '用戶表'
        verbose_name_plural = verbose_name
​
    def __str__(self):
        return self.username

 

  • serializers.py

1) 前臺提交多種登陸信息都採用一個key,因此後臺能夠自定義反序列化字段進行對應
2) 序列化類要處理序列化與反序列化,要在fields中設置model綁定的Model類全部使用到的字段
3) 區分序列化字段與反序列化字段 read_only | write_only
4) 在自定義校驗規則中(局部鉤子、全局鉤子)校驗數據是否合法、肯定登陸的用戶、根據用戶簽發token
5) 將登陸的用戶與簽發的token保存在序列化類對象中 返回給前端

 

from rest_framework import serializers
from . import models
import re
from rest_framework_jwt.serializers import jwt_payload_handler
from rest_framework_jwt.serializers import jwt_encode_handler
​
class UserModelSerializer(serializers.ModelSerializer):
    # 自定義反序列字段:
    # 1.必定要設置write_only,只參與反序列化,不會與model類字段映射
    # 2.要在fields中註冊自定義反序列化字段
    # 3.自定義反序列化字段不要與model類表中的字段同樣
    usr = serializers.CharField(write_only=True)
    pwd = serializers.CharField(write_only=True)
    class Meta:
        model = models.User
        fields = ['usr', 'pwd', 'username', 'mobile', 'email']
        # 系統校驗規則
        extra_kwargs = {
            'username': {'read_only': True},
            'mobile': { 'read_only': True},
            'email': {'read_only': True},
        }
​
    def validate(self, attrs):
        usr = attrs.get('usr')
        pwd = attrs.get('pwd')
​
        # 多方式登陸:各分支處理獲得該方式下對應的用戶
        if re.match(r'.+@.+', usr):
            user_query = models.User.objects.filter(email=usr)
        elif re.match(r'1[3-9][0-9]{9}', usr):
            user_query = models.User.objects.filter(mobile=usr)
        else:
            user_query = models.User.objects.filter(username=usr)
        user_obj = user_query.first()
        # 根據user_obj校驗密碼是否正確
        if user_obj and user_obj.check_password(pwd):
            # 簽發token:獲得登陸用戶,簽發token並存儲在實例化對象中
            payload = jwt_payload_handler(user_obj)
            token = jwt_encode_handler(payload)
            # 將當前用戶與簽發的token都保存在序列化對象中
            self.user = user_obj
            self.token = token
            return attrs
        raise serializers.ValidationError({'data':'數據有誤'})
  • views.py

#實現多方式登錄簽發token:帳號、手機號、郵箱等登錄
1) 禁用認證與權限組件
2) 拿到前臺登陸信息,交給序列化類
3) 序列化類校驗獲得登陸用戶與token存放在序列化對象中
4) 取出登陸用戶與token返回給前臺

 

from . import serializers, models
from utils.response import APIResponse
class LoginAPIView(APIView):
    # 1) 禁用認證與權限組件
    authentication_classes = []
    permission_classes = []
    def post(self, request, *args, **kwargs):
        # 2) 拿到前臺登陸信息,交給序列化類,規則:帳號用usr傳,密碼用pwd傳
        user_ser = serializers.UserModelSerializer(data=request.data)
        # 3) 序列化類校驗獲得登陸用戶與token,存放在序列化對象中
        user_ser.is_valid(raise_exception=True)
        # 4) 取出登陸用戶與token返回給前臺
        return APIResponse(token=user_ser.token, results=serializers.UserModelSerializer(user_ser.user).data)

總結:

# 自定義簽發token
本質就是獲取前端post請求發來的登陸條件(username,email,mobile...)和密碼
自定義反序列類,反序列化登陸條件和密碼,校驗經過後調用jwt_payload_handler,jwt_encode_handler完成簽發

 

案例:自定義認證反爬規則的認證類

  • authentications.py

import jwt
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication
from rest_framework_jwt.authentication import jwt_decode_handler
from rest_framework.exceptions import AuthenticationFailed
​
# 自定義token校驗規則 # 1.繼承BaseJSONWebTokenAuthentication
class JWTAuthentication(BaseJSONWebTokenAuthentication):
    # 2.重寫authentication方法
    def authenticate(self, request):
        # 3.獲取token
        jwt_token = request.META.get('HTTP_AUTHORIZATION')
        # 4.自定義校驗規則 如: auth token jwt
        token = self.parse_jwt_token(jwt_token)
        if token is None:
            return None  # 遊客
# 5.根據token拿到payload | token => payload
        try:
            payload = jwt_decode_handler(token)
        except jwt.ExpiredSignature:
            raise AuthenticationFailed('token已過時')
        except:
            raise AuthenticationFailed('非法用戶')
        # 6.根據payload拿到user | payload => user
        user = self.authenticate_credentials(payload)
        return user
​
    # 規則方法
    def parse_jwt_token(self, jwt_token):
        # 按空格切分
        tokens = jwt_token.split()
        # 校驗規則
        if len(tokens) != 3 or tokens[0].lower() != 'auth' or tokens[2].lower() != 'jwt':
            return None  # 遊客
        return tokens[1]

 

  • views.py

from rest_framework.views import APIView
from utils.response import APIResponse
# 必須登陸後才能訪問 - 經過了認證權限組件
from rest_framework.permissions import IsAuthenticated
# 自定義jwt校驗規則
from .authentications import JWTAuthentication
class UserDetail(APIView):
  # 局部配置認證組件,這裏的認證組件是自定義的 authentication_classes
= [JWTAuthentication] permission_classes = [IsAuthenticated] def get(self, request, *args, **kwargs): return APIResponse(results={'username': request.user.username})

 

總結:

# 自定義token校驗規則
自定義校驗token本質是對token加的鹽進行校驗
1 在視圖類中配置自定義的token校驗器
2 自定義token校驗器,重寫authenticate方法
3 從請求頭中拿到token,按規則校驗
4 校驗成功在按步驟: token => payload => user 將user返回
相關文章
相關標籤/搜索