DRF ---- JWT

JWT

jwt认证的优点:

  服务器不要存储token,token交给每一个客户端自己存储,服务器压力小

  服务器存储的是 签发和校验token 两段算法,签发认证的效率高

  算法完成各集群服务器同步成本低,路由项目完成集群部署(适应高并发)

1 . 工作原理

2)每一部分都是一个json字典加密形参的字符串
3)头部和载荷采用的是base64可逆加密(前台后台都可以解密)
4)签名采用hash256不可逆加密(后台校验采用碰撞校验)
5)各部分字典的内容:
    头部:基础信息 - 公司信息、项目组信息、可逆加密采用的算法
    载荷:有用但非私密的信息 - 用户可公开信息、过期时间
    签名:头部+载荷+秘钥 不可逆加密后的结果
    注:服务器jwt签名加密秘钥一定不能泄露
签发token:固定的头部信息加密.当前的登陆用户与过期时间加密.头部+载荷+秘钥生成不可逆加密
校验token:头部可校验也可以不校验,载荷校验出用户与过期时间,头部+载荷+秘钥完成碰撞检测校验token是否被篡改

2 . drf-jwt

下载

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

安装

pip install djangorestframework-jwt

使用

官方接口文档

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

模块不需要注册 因为没有涉及到数据库的映射

提供了view.py 有 4 个类 分别为:

class JSONWebTokenAPIView(APIView):
class ObtainJSONWebToken(JSONWebTokenAPIView): # 获得token 基于权限六表的
class RefreshJSONWebToken(JSONWebTokenAPIView): # 刷新token
class VerifyJSONWebToken(JSONWebTokenAPIView):  # 校验token
# 三个函数
obtain_jwt_token = ObtainJSONWebToken.as_view()
refresh_jwt_token = RefreshJSONWebToken.as_view()
verify_jwt_token = VerifyJSONWebToken.as_view()
# ObtainJSONWebToken 视图类就是通过 username 和 password 得到 user 对象然后签发 token
from rest_framework_jwt.views import ObtainJSONWebToken, obtain_jwt_token
urlpatterns = [
    url(r'^jogin/$', ObtainJSONWebToken.as_view()), # 可替换成下面的 里面有post方法
    url(r'^jogin/$', obtain_jwt_token),
]

认证 - 校验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" 格式的认证字符串

3.签发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)

jwt_payload_handler

jwt_encode_handler

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

4.校验token

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

jwt_decode_handler

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)

5.案例:实现多方式登陆签发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

from rest_framework import serializers
from . import models
import re

# 拿到前台token的两个函数: user => payload => token
# from rest_framework_jwt.settings import api_settings
# jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
# jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
from rest_framework_jwt.serializers import jwt_payload_handler
from rest_framework_jwt.serializers import jwt_encode_handler


# 1) 前台提交多种登录信息都采用一个key,所以后台可以自定义反序列化字段进行对应
# 2) 序列化类要处理序列化与反序列化,要在fields中设置model绑定的Model类所有使用到的字段
# 3) 区分序列化字段与反序列化字段 read_only | write_only
# 4) 在自定义校验规则中(局部钩子、全局钩子)校验数据是否合法、确定登录的用户、根据用户签发token
# 5) 将登录的用户与签发的token保存在序列化类对象中
class UserModelSerializer(serializers.ModelSerializer):
    # 自定义反序列字段:一定要设置write_only,只参与反序列化,不会与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()

        # 签发:得到登录用户,签发token并存储在实例化对象中
        if user_obj and user_obj.check_password(pwd):
            # 签发token,将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返回给前台
import re
from . import serializers, models
from utils.response import APIResponse

from rest_framework_jwt.serializers import jwt_payload_handler
from rest_framework_jwt.serializers import jwt_encode_handler

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)

    # "一根筋" 思考方式:所有逻辑都在视图类中处理
    def my_post(self, request, *args, **kwargs):
        usr = request.data.get('usr')
        pwd = request.data.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()
        if user_obj and user_obj.check_password(pwd):
            payload = jwt_payload_handler(user_obj)
            token = jwt_encode_handler(payload)
            return APIResponse(results={'username': user_obj.username}, token=token)
        return APIResponse(data_msg='不可控错误')

6.案例:自定义认证反爬规则的认证类

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
class JWTAuthentication(BaseJSONWebTokenAuthentication):
    def authenticate(self, request):
        jwt_token = request.META.get('HTTP_AUTHORIZATION')

        # 自定义校验规则:auth token jwt
        token = self.parse_jwt_token(jwt_token)

        if token is None:
            return None

        try:
            # token => payload
            payload = jwt_decode_handler(token)
        except jwt.ExpiredSignature:
            raise AuthenticationFailed('token已过期')
        except:
            raise AuthenticationFailed('非法用户')
        # payload => user
        user = self.authenticate_credentials(payload)

        return (user, token)

    # 自定义校验规则:auth token jwt,auth为前盐,jwt为后盐
    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})
posted @ 2020-01-08 10:54  LD_Dragon_sky  阅读(241)  评论(0编辑  收藏  举报