认证组件
rest_framework的认证组件是为了判断用户有没有合法身份,一般认为没有登录或者没有授权即为不合法。
rest_framework在什么时候运行认证组件
说到rest_framework的认证组件,就要说到Django的CBV了。rest_framework模块的APIView类重写了CBV中的dispatch方法。
def dispatch(self, request, *args, **kwargs):
"""
`.dispatch()` is pretty much the same as Django's regular dispatch,
but with extra hooks for startup, finalize, and exception handling.
"""
self.args = args
self.kwargs = kwargs
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate?
try:
self.initial(request, *args, **kwargs)
# Get the appropriate handler method
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(),
self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
response = handler(request, *args, **kwargs)
except Exception as exc:
response = self.handle_exception(exc)
self.response = self.finalize_response(request, response, *args, **kwargs)
return self.response
其中在运行请求方式对应的视图函数之前,执行了initial方法。APIView类中的initial就是专门执行rest_framework组件的入口。
def initial(self, request, *args, **kwargs):
"""
Runs anything that needs to occur prior to calling the method handler.
"""
self.format_kwarg = self.get_format_suffix(**kwargs)
# Perform content negotiation and store the accepted info on the request
neg = self.perform_content_negotiation(request)
request.accepted_renderer, request.accepted_media_type = neg
# Determine the API version, if versioning is in use.
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme
# Ensure that the incoming request is permitted
self.perform_authentication(request)
self.check_permissions(request)
self.check_throttles(request)
其中的perform_authentication就是执行认证组件的方法。 查看perform_authentication方法的代码,发现运行的是request对象的user方法。
def perform_authentication(self, request):
"""
Perform authentication on the incoming request.
Note that if you override this and simply 'pass', then authentication
will instead be performed lazily, the first time either
`request.user` or `request.auth` is accessed.
"""
request.user
再看到request对象是initialize_request方法的返回值,查看initialize_request方法的代码。
def initialize_request(self, request, *args, **kwargs):
"""
Returns the initial request object.
"""
parser_context = self.get_parser_context(request)
return Request(
request,
parsers=self.get_parsers(),
authenticators=self.get_authenticators(),
negotiator=self.get_content_negotiator(),
parser_context=parser_context
)
initialize_request方法返回的request对象是Request类的实例化对象,所以user方法应该在Request类中。
@property
def user(self):
"""
Returns the user associated with the current request, as authenticated
by the authentication classes provided to the request.
"""
if not hasattr(self, '_user'):
with wrap_attributeerrors():
self._authenticate()
return self._user
查看_authenticate方法,才找到了执行认证组件的方法。authenticator.authenticate(self)中的authenticator是组件实例化的对象,authenticate是认证组件的实现认证功能的方法,self是request对象。
def _authenticate(self):
"""
Attempt to authenticate the request using each authentication instance
in turn.
"""
for authenticator in self.authenticators:
try:
user_auth_tuple = authenticator.authenticate(self)
except exceptions.APIException:
self._not_authenticated()
raise
if user_auth_tuple is not None:
self._authenticator = authenticator
self.user, self.auth = user_auth_tuple
return
self._not_authenticated()
rest_framework自带的认证组件
-
BasicAuthentication
-
SessionAuthentication
-
TokenAuthentication
-
RemoteUserAuthentication
自定义认证组件
自定义认证组件,需要继承rest_framework.authentication.BaseAuthentication,并重写authenticate方法即可。
注意authenticate的返回值一般是一个有两个元素的元组。下面是继承BaseAuthentication的子类的TokenAuthentication类的自定义组件示例。
from rest_framework.authentication import TokenAuthentication
from rest_framework import exceptions
class UserTokenAuthentication(TokenAuthentication):
keyword = 'XqCircleToken'
def get_model(self):
if self.model is not None:
return self.model
return UserToken
def authenticate(self, request):
model = self.get_model()
key = request.META.get('HTTP_AUTHORIZATION', '')
if not key:
raise exceptions.AuthenticationFailed(_('Invalid token.'))
key = key.split()[1]
try:
token = model.objects.select_related('user').get(key=key)
except model.DoesNotExist:
raise exceptions.AuthenticationFailed(_('Invalid token.'))
return token.user, token
这里需要注意,有两种方法给函数添加认证功能:
第一种:
在对应函数下添加:
authentication_classes = [LoginAuth, ]
[]内可以添加多个值,如果前面的方法中return了值,后面的方法就不会继续执行,
只有前面的方法中return了None,才会继续执行后面的方法
第二种:
在settings中全局配置:
REST_FRAMEWORK={
'DEFAULT_AUTHENTICATION_CLASSES':['app01.MyAuth.LoginAuth',]
}
配置之后所有的方法都需认证,当想局部禁用认证时,需在对应函数中添加下面这句
authentication_classes = []