def authenticate(self, request):
return (self.force_user, self.force_token)
def _not_authenticated(self):
"""
Set authenticator, user & authtoken representing an unauthenticated request.
Defaults are None, AnonymousUser & None.
"""
self._authenticator = None
if api_settings.UNAUTHENTICATED_USER:
self.user = api_settings.UNAUTHENTICATED_USER()
else:
self.user = None
if api_settings.UNAUTHENTICATED_TOKEN:
self.auth = api_settings.UNAUTHENTICATED_TOKEN()
else:
self.auth = None
api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS)
'UNAUTHENTICATED_USER': 'django.contrib.auth.models.AnonymousUser',
'UNAUTHENTICATED_TOKEN': None,
from django.shortcuts import HttpResponse
from rest_framework.views import APIView#导入rest_framework的试图类
from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions
from . import models
class CustomAuthenticate(BaseAuthentication):
"""
All authentication classes should extend BaseAuthentication.
"""
def authenticate(self, request):
"""
Authenticate the request and return a two-tuple of (user, token).
"""
tk = request.query_param.get('tk') #获取用户输入的token 简化写法,就直接在url中传参了
token_obj = models.Token.objects.filter(token=tk).first()
if token_obj:
return (token_obj.user,token_obj)
raise exceptions.AuthenticationFailed('请登录') #抛出异常表示不允许匿名用户访问
# else:
# return (None,None)
def authenticate_header(self, request):
"""
Return a string to be used as the value of the `WWW-Authenticate`
header in a `401 Unauthenticated` response, or `None` if the
authentication scheme should return `403 Permission Denied` responses.
"""
pass
class TestView(APIView):
authentication_classes = [CustomAuthenticate,] #应用认证配置类
def get(self,request,*args,**kwargs):
return HttpResponse('ok')