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

看到一篇大神的文章:

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是继承APIViewView类:

 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

求大手子轻喷,留着以后备用吧!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值