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文件注册认证类
}
相关推荐
风象南29 分钟前
很多人说,AI 让技术平权了,小白也能乱杀老师傅 ?
人工智能·后端
雨中飘荡的记忆2 小时前
ElasticJob分布式调度从入门到实战
java·后端
Se7en2582 小时前
推理平台全景
后端
大漠_w3cpluscom2 小时前
你学不会 CSS,不是笨,是方向错了
后端
花酒锄作田3 小时前
使用 pkgutil 实现动态插件系统
python
cipher6 小时前
ERC-4626 通胀攻击:DeFi 金库的"捐款陷阱"
前端·后端·安全
毅航6 小时前
自然语言处理发展史:从规则、统计到深度学习
人工智能·后端
JxWang056 小时前
Task04:字符串
后端
前端付豪7 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain