Django-rest-framework(DRF)如何实现自定义认证

一、创建自定义类

python 复制代码
import datetime
from django.conf import settings
from rest_framework.authentication import BasicAuthentication
from rest_framework.exceptions import AuthenticationFailed
from base.models import User
import jwt
from jwt import exceptions


def create_token(payload):  # 创建token
    salt = settings.SECRET_KEY
    headers = {
        'typ': 'jwt',
        'alg': 'HS256',
    }
    payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(minutes=3)  # 设置token的有效时间
    token = jwt.encode(payload=payload, key=salt, headers=headers, algorithm='HS256')
    return token


class MyAuthentication(BasicAuthentication):  #继承基础的认证类
    def authenticate(self, request):
        token = request.META.get('HTTP_AUTHORIZATION')
        if token:
            salt = settings.SECRET_KEY
            payload = None
            try:
                payload = jwt.decode(token, salt, algorithms='HS256', verify=True)
            except exceptions.ExpiredSignatureError:
                raise AuthenticationFailed({'code': '1000', 'msg': 'token已经失效'})
            except jwt.DecodeError:
                raise AuthenticationFailed({'code': '1001', 'msg': 'token认证失败'})
            except jwt.InvalidTokenError:
                raise AuthenticationFailed({'code': '1002', 'msg': '非法的token'})
            user_objects = User.objects.filter(username=payload['user']['username']).first()
            return user_objects, token
        else:
            raise AuthenticationFailed({'code': '1003', 'msg': '没有获取到token'})

    def authenticate_header(self, request):
        return 'API'

二、全局使用

python 复制代码
REST_FRAMEWORK = {
    'UNAUTHENTICATED_USER': None,
    'DEFAULT_AUTHENTICATION_CLASSES': ['utils.auth.MyAuthentication'],  # 全局使用,settings文件注册认证类
}
相关推荐
高洁011 小时前
具身智能感知系统底层原理
人工智能·python·深度学习·机器学习·transformer
我就是不信1 小时前
Java8 lambda 表达式 forEach 如何提前终止?
开发语言·windows·python
全栈弄潮儿1 小时前
Python实战第9期:文件操作
后端·python·编程语言
小星星_ios1 小时前
从 3Blue1Brown 到 NumPy:手写一个神经网络训练 MNIST
人工智能·python·神经网络
神魔皆以血嗜1 小时前
Java 实现简单状态机(订单状态流转)
java·后端
Maxwin1 小时前
Manim 竖屏画布选 9×16 还是 4.5×8?从 font_size 和每单位像素数说起
python·ffmpeg
zz在掘金337082 小时前
MongoDB 脚本速查
后端
随性而行3602 小时前
企业微信 API 如何实现业务消息自动通知?接口应用场景解析
java·人工智能·后端·微信·机器人·企业微信
Mav2 小时前
[个人学习记录]从零构建高性能 LLM 推理网关:长连接优雅停机(Graceful Drain)、K8s 探针联动与 Context 底层哲学
后端
昭昭日月明2 小时前
使用 Ragas 量化 RAG
python·langchain·ai编程