您的位置:首页 > 编程语言 > Go语言

Django REST framework之认证权限流程源码分析

2018-03-02 14:23 1331 查看

看到一篇大神的文章:

https://www.jianshu.com/p/a0741a463422

下面是我总结的一个大概流程,精简了一下:

django 的url请求对应一个视图函数as_view函数,其中调用rest_framework/views.py中的dispatch函数,这个函数会根据request的请求方法,去调用我们在view对象中定义的对应的方法:

urlpatterns = [
url(
r"^test/?", testView.as_view(),
)]

testView是继承APIView的View类:

class TestView(APIView):
authentication_classes = (

BasicAuthentication,
SessionAuthentication,
TokenAuthentication,

)
permission_classes = (

IsAuthenticated,
)

def get(self,request):
pass

如果是get请求会调用as_view中的dispatch方法,dispatch根据request.Method调用
对应的get的方法,url->视图函数

权限认证是在dispatch中做的
self.as_view()
||
vv
def dispatch(request,*args,**kwargs):
||
VV
self.initial(request,*args,**kwargs):
||
VV

self.perform_authentication
self.check_permissions
self.check_throttles

验证某个用户:
perform_authentication(request)
request.user

request.user其实是一个@property函数
里面有个self._authenticate()方法
_authenticate(self)方法中验证用户就是authenticator.authenticate(self)

self.authenticators从哪里来?就是从视图函数中的authentication_classes中的来,关于对view控制的其他类都在rest_framework/views.py的APIView类中定义了。

在BasicAuthentication中必须实现authenticate方法,并且返回一个用户,并赋值给request.user,这个request.user就是系统中进行用户认证的user对象,后续的权限认证
就是通过该user为依据进行判断是否有某个api的权限

user = authenticate(**credentials)
||
vv
user = backend.authenticate(**credentials)

这个authenticate是django的authenticate方法:
||
vv
主要是去数据库校验数据,校验结束!!!

接着执行self.check_permissions(self,request):
如果权限不通过,那么会执行self.permission_denied,然后这个异常会在dispatch
函数中被捕捉,当做结果传递给response。

当一次授权通过后,再一次访问这个API时,用户名密码从哪来?
cookie和session


求大手子轻喷,留着以后备用吧!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  drf