REST framework 的认证组件是在* APIView *dispatch
下执行的。跟着源码过了下,了解它的实现过程。
上图源代码中的self.authenticators就是一个认证组件类的一个列表,我们在接下来后面的自定义认证组件时,就要注意这里面的源代源内容,自定义类的类名可以自己起,而类中的方法名是有特定的名字authenticator
。因为源代源中user_auth_tuple=authenticator.authenticate(self)
已经固定了这个方法名。另外还要注意一点,如果列表中只有一个认证组件的话,可以返回一个元组,但如果是多个认证组件的话,就只能在最后一个自定义认证组件还回元组,或是都返回None。不然一有返回元组,就退出了for循环,接下来的认证组件都不会执行到。
到了这,就差不多里已经出来结果了,只需要分析self是谁,如果自己类中定义authentication_classes
就是自定的,如果没有,就用默认的,我们接下来看看如果没有自定义的,REST framework 是如何执行到默认的认证组件。
这上面的两个组件就是默认的组件。
自定义一个认证组件:
from rest_framework.exceptions import AuthenticationFailed
class TokenAuth(AuthenticationFailed):
def authenticate(self,request):
token=request.GET.get('token',None)
token_obj=UserToken.objects.filter(token=token).first()
if token_obj:
return token_obj.user.user,token_obj
else:
raise AuthenticationFailed('认证失败!')
def authenticate_header(self, request):
pass
如果继承BaseAuthentication类则不用定义authenticate_header
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from api.models import UserToken
class LoginAuth(BaseAuthentication):
def authenticate(self, request):
token=request.GET.get("token")
token_obj=UserToken.objects.filter(token=token).first()
if token_obj:
return token_obj.user,token_obj.token
else:
raise AuthenticationFailed("认证失败")