JWT LL

 

1、工作原理

""" 
1) jwt = base64(头部).base(载荷  payload).hash256(base64(头部).base(载荷).密钥)
2) base64是可逆的算法、hash256是不可逆的算法
3) 密钥是固定的字符串,保存在服务器
"""

 

2、drf-jwt

官网
http://getblimp.github.io/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"
}
"""

 

3、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 . import models
class UserModelSerializers(serializers.ModelSerializer):
    class Meta:
        model = models.User
        fields = ['username']

 

自定义response:user/utils.py
from .serializers import UserModelSerializers
def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'status': 0,
        'msg': 'ok',
        'data': {
            'token': token,
            'user': UserModelSerializers(user).data
        }
    }

 

基于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):
        jwt_value = get_authorization_header(request)

        if not jwt_value:
            raise AuthenticationFailed('Authorization 字段是必须的')
        try:
            payload = jwt_decode_handler(jwt_value)
        except jwt.ExpiredSignature:
            raise AuthenticationFailed('签名过期')
        except jwt.InvalidTokenError:
            raise AuthenticationFailed('非法用户')
        user = self.authenticate_credentials(payload)

        return user, jwt_value

 解读:

JSONWebTokenAuthentication 是一个自定义身份验证类,它通常用于 Django REST framework 中实现
基于 JSON Web Token (JWT) 的用户认证。
这个类继承自 BaseJSONWebTokenAuthentication,并覆盖了 authenticate 方法以处理 JWT 的验证逻辑。 在该方法中: 通过 get_authorization_header(request) 函数从请求的头部(通常是
'Authorization' 字段)获取 JWT 值。 如果没有找到 JWT 值,则抛出 AuthenticationFailed 异常,提示 "Authorization 字段是必须的"。 尝试使用 jwt_decode_handler(jwt_value) 解码提供的 JWT。这个解码函数会检查签名的有效性和 token 是否过期等。 如果签名已过期,会抛出 ExpiredSignature 异常,此时捕获异常并抛出 AuthenticationFailed,提示 "签名过期"。 如果 JWT 校验失败(比如 token 格式错误、密钥不匹配或其他任何无效情况),会抛出 InvalidTokenError 异常,
此时也会捕获异常并抛出 AuthenticationFailed,提示
"非法用户"。 如果 JWT 解码成功,调用 self.authenticate_credentials(payload) 来进一步验证 payload 中携带的用户凭证信息是否有效,
并据此获取或创建对应的用户对象。 如果用户凭证验证成功,返回一个包含用户对象和原始 JWT 值的元组 (user, jwt_value)。这样,经过此身份验证流程后,
合法的用户就能通过 JWT 进行后续的 API 请求授权访问。

 

全局启用: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
import re
from .models import User
from django.contrib.auth.backends import ModelBackend
class JWTModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            if re.match(r'^1[3-9]\d{9}$', username):
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)
        except User.DoesNotExist:
            return None
        if user.check_password(password) and self.user_can_authenticate(user):
            return user

 

配置多方式登录: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)

 

posted @ 2024-03-13 15:06  朱饱饱  阅读(12)  评论(0)    收藏  举报