Django中继承APIView后,DRF认证方式的逻辑分析

        认证逻辑一共分为三个部分,下面一一解说,并配生动形象的例子帮助理解......(应该比较生动)......

一、

        APIView源码如下:

class APIView(View):

    # The following policies may be set at either globally, or per-view.
    renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
    parser_classes = api_settings.DEFAULT_PARSER_CLASSES
    authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES
    throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES
    permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES
    content_negotiation_class = api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS
    metadata_class = api_settings.DEFAULT_METADATA_CLASS
    versioning_class = api_settings.DEFAULT_VERSIONING_CLASS

    # Allow dependency injection of other settings to make testing easier.
    settings = api_settings

        红色字体的语义为:用户认证方式=配置文件settings中的'DEFAULT_AUTHENTICATION_CLASSES'这个类。

        'DEFAULT_AUTHENTICATION_CLASSES'语义为:默认的认证方式。

        进入配置文件中,找到默认的认证方式,代码如下:

# 配置DRF
REST_FRAMEWORK = {
    # 配置JWT作为验证后端
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    )
}

        该认证方式的认证逻辑为从上到下执行,优先通过JWT认证,如果它验证不通过,才用后面的Session和Basic验证。

二、

        知道了认证方式之后就要开始认证了,下面是具体的认证的代码:

 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

        认证逻辑为:如果user取到,就登录;取不到就未登录。

        如果要实现非登陆用户也可以访问视图,则重写该方法,直接改写成pass,代码如下:

def perform_authentication(self, request):
        """
        重写父类的用户验证方法,不在进入视图以前检查JWT
        保证用户未登录也可以进入下面的请求方法,不让它执行request.user
        """
        pass

三、

        写完认证代码后,就要开始设置认证程度了,代码如下:

from rest_framework.peimissions import IsAuthenticated, IsAdminUser


class UserDetailView(APIView)
    permission_classes = [IsAuthenticated]

        permission_classes表示要认证到什么程度,[IsAuthenticated]表示必须是登录用户才可以访问。

补充说明:

一、二、三的关系好比是:

        一,表示你吃饭的方式,用筷子吃还是勺子吃;
        二,就是筷子或勺子;
        三,则表示要吃到几分饱。


猜你喜欢

转载自blog.csdn.net/jingzhunbiancheng/article/details/80959492