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文件注册认证类
}
相关推荐
码途行者6 小时前
每天10分钟学Go:第17课 接口interface-只规定“能做什么“,不管它是什么
开发语言·后端·golang
timeDifference₇7 小时前
Python Vibe Coding实操实验报告
开发语言·jvm·python
geovindu8 小时前
python:DecisionTree
开发语言·后端·python·算法
Cosolar8 小时前
从 Java 21 升到 25、Spring Boot 3 升 4:一次可复现的迁移踩坑实录
java·后端·面试
怒放的生命19919 小时前
代码知识库 RAG 问答系统 —— 从 0 到 1 实现教程
python·状态模式·fastapi·全栈开发·ai agent应用开发
geovindu10 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
码事漫谈10 小时前
黄仁勋的来时路
后端
bai27310 小时前
path.join('C:\a', '\b') 给我 C:\a\b,path.resolve 给 C:\b:Windows 上 51 行路径实测
javascript·后端
hackhase10 小时前
Django 多表数据整合:7 张异构表如何收敛成 4 类页面
后端·mysql
fengkai454510 小时前
Python运维
运维·python·监控·psutil·ipy