有两种方法添加验证
from rest_framework.authentication import BaseAuthentication,BasicAuthentication, SessionAuthentication, TokenAuthentication
1. BasicAuthentication: 基于用户名密码
2. SessionAuthentication:基于session
3. TokenAuthentication:基于token
全局验证添加方法
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
}
authentication_classes = [
MyAuthentication
]
自定义验证
- 新建一个 Authentication文件
- 创建一个类继承 BaseAuthentication
class MyAuthentication(BaseAuthentication):
def authenticate(self,request):
token = request.META.get('HTTP_TOKEN')
obj = UserToken.objects.filter(token=token).first()
if not obj:
raise exceptions.AuthenticationFailed('请检查你的token')
else:
return (obj.user,obj)