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文件注册认证类
}
相关推荐
程序新视界17 分钟前
什么是MySQL JOIN查询的驱动表和被驱动表?
数据库·后端·mysql
爬虫程序猿32 分钟前
把 1688 商品详情搬进 MySQL:PHP 爬虫全链路实战(2025 版)
爬虫·python·音视频
无限进步_1 小时前
C语言文件操作全面解析:从基础概念到高级应用
c语言·开发语言·c++·后端·visual studio
咖啡教室1 小时前
每日一个计算机小知识:IP和域名
后端
Q_Q5110082851 小时前
python+django/flask婚纱摄影拍照管理系统
spring boot·python·django·flask·node.js·php
咖啡教室1 小时前
每日一个计算机小知识:Host
后端
可触的未来,发芽的智生1 小时前
触摸未来2025-10-18:生成文字的小宇宙矩阵溯源
人工智能·python·神经网络·程序人生·自然语言处理
_码力全开_1 小时前
P1005 [NOIP 2007 提高组] 矩阵取数游戏
java·c语言·c++·python·算法·矩阵·go
咖啡教室2 小时前
每日一个计算机小知识:Bit和Byte(比特和字节)
后端