1.创建py文件authentications.py(名字自定义)
2.from rest_framework.authentication import BaseAuthentication
构建class MyAuthentication(BaseAuthentication)必须继承BaseAuthentication
3.重写抽象方法def authenticate(self, request):必须重写
返回值是一个元组(user,None)用户必须返回,第二个返回值自定义,没有就填None
from django.core.cache import cache
from rest_framework.authentication import BaseAuthentication
from rest_framework.response import Response
from index.models import BbsUser
class MyAuthentication(BaseAuthentication):
def authenticate(self, request):
get请求不需要认证
# if request.method == "GET":
# return None
try:
token=request.query_params.get('token')
if not token:
raise AuthenticationFailed('请登录')
uid=cache.get(token)
if not uid:
raise AuthenticationFailed('登录已过期,请重新登录')
user=BbsUser.objects.filter(uid=int(uid))
if not user:
raise AuthenticationFailed('用户不存在')
return user,None
except:
raise AuthenticationFailed('认证失败,请重新登录')
局部认证
#方法前
authentication_classes = MyAuthentication,
全局认证
#settings中
REST_FRAMEWORK = {
# 'DEFAULT_AUTHENTICATION_CLASSES': (
# 'App.autentications.MyAuthentication',
# )
#}
版权声明:本文为qq_43665151原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。