
本文介绍的是 django rest_framework的认证方式.
Token、Session、RemoteUser、jwt等认证方式。前三种是框架自带的,而jwt需要安装第三方库djangorestframework-jwt,然后使用。
以下是认证源码认证流程.
ApiView.as_view中. 
ApiView继承Django的View,然后调用View.as_view 
View中调用dispatch方法,因为ApiView实现dispatch方法,所以调用的是ApiView.dispatch而不是View.dispatch. 
ApiView.dispatch中将django.request再次封装成框架的rest_framework.request 



ApiView.perform_authentication开始认证 
request.user,然后再调用request._authentication进行循环遍历所有注入的Authentiation类中authenticate方法进行认证,认证成功则返回user和auth两个结果
可以自定义认证类,只需要继承BaseAuthentication类,然后实现authenticate方法即可,然后将该类注入到request即可.
或者使用框架自带的认证类也可。
是框架自带的认证方式之一.
INSTALLED_APPS = [
...
'rest_framework.authtoken']然后使用python manage.py migrate,会创建authtoken表,该表连接auth_user.表,每个用户都有对应一个token,用户每次访问带有该token,系统就能通过token得到当前user.
在TestView添加TokenAuthentication认证, 路由到TestView时,会调用该类中的authenticate方法,通过token获取到user.
view.py
from rest_framework.authentication import TokenAuthentication
class TestView(APIView):
authentication_classes = (TokenAuthentication,)
def get(self, *args, **kwargs):
return HttpResponse(self.request.user)任何路由请求需要通过Token认证.
settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
]
}鉴于以上缺陷,使用jwt更加优秀.
drf中session认证,是通过django SessionMiddleware和AuthenticationMiddleware中将user存储到request中,然后获取到的.
