认证的实现
- 写一个类,继承BaseAuthentication,也可以不继承这个类,重写authenticate方法,认证的逻辑写在里面,认证通过,返回两个值,一个值是user(可以自己生成,也可以去查数据库获取),最终给了Request对象,认证失败,抛异常APIException(它是父类)或者AuthenticationFailed(它是子类)
- 全局使用,局部使用,局部配置优先于全局
认证源码分析
perform_authentication(self, request)里面就一句:request.user
# 去Request类中找request.user属性或方法,这个方法里面关键就一句:self._authenticate()
class 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
def _authenticate(self):
"""
Attempt to authenticate the request using each authentication instance
in turn.
"""
# self.authenticators是自己在视图类中配置的认证类:authentication_classes=[认证类1,认证类2...] 的对象列表
for authenticator in self.authenticators:
try:
# 这些认证类继承了BaseAuthentication,这个类里面有个authenticate方法,继承了这个类,就要重写这个方法,否则会报错
user_auth_tuple = authenticator.authenticate(self)# 这个self是Request类的对象
except exceptions.APIException:
self._not_authenticated()
raise
# 如果配置多个认证类,要把返回两个值的放到最后,否则,后面的认证类不会执行,因为遇到return,函数会结束
if user_auth_tuple is not None:
self._authenticator = authenticator
self.user, self.auth = user_auth_tuple
return
self._not_authenticated()