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文件注册认证类
}
相关推荐
m0_734949795 小时前
MySQL如何配置定时清理过期备份文件_find命令与保留周期策略
jvm·数据库·python
m0_514520575 小时前
MySQL索引优化后性能没提升_通过EXPLAIN查看索引命中率
jvm·数据库·python
2601_949817726 小时前
Spring Boot3.3.X整合Mybatis-Plus
spring boot·后端·mybatis
H Journey6 小时前
Python 国内pip install 安装缓慢
python·pip·install 加速
uNke DEPH6 小时前
Spring Boot的项目结构
java·spring boot·后端
zhenxin01226 小时前
Spring Boot 3.x 系列【3】Spring Initializr快速创建Spring Boot项目
spring boot·后端·spring
Polar__Star7 小时前
如何在 AWS Lambda 中正确使用临时凭证生成 S3 预签名 URL
jvm·数据库·python
前端一小卒7 小时前
前端工程师的全栈焦虑,我用 60 天治好了
前端·javascript·后端
不停喝水7 小时前
【AI+Cursor】 告别切图仔,拥抱Vibe Coding: AI + Cursor 开启多模态全栈新纪元 (1)
前端·人工智能·后端·ai·ai编程·cursor
oyzz1207 小时前
Spring EL 表达式的简单介绍和使用
java·后端·spring