from django.core.cache import cache
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from App.models import User
class MyAuthentication(BaseAuthentication):
# 自定义的认证类必须实现Authentication
# 认证的规则,自己定义,成功返回一个二元组(user,value)
def authenticate(self, request):
# token可以从请求的get参数中获取
token = request.query_params.get('token')
if not token:
raise AuthenticationFailed("没有token")
uid = cache.get(token)
try:
user = User.objects.get(pk=uid)
if user:
return user, None
else:
raise AuthenticationFailed("token不存在")
except Exception as e:
raise AuthenticationFailed("token不合法")
用户认证设置
最新推荐文章于 2023-12-19 14:00:27 发布