认证于权限

  • drf认证组件
  • 在主应用的settings中配置,此时的认证和权限是全局的,若部分视图不需要权限于认证处理只需要将类名置空即可
  • """drf配置信息"""
    REST_FRAMEWORK = {
        #循环认证,一旦认证成功则不会往下再去认证
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'Restful_api.authentication.CustomerDefinedAuthentication',  # 自定义认证
            'rest_framework.authentication.SessionAuthentication',#session认证
            'rest_framework.authentication.BasicAuthentication',#基础认证
    
        ],
        # 'DEFAULT_PERMISSION_CLASSES': [
        #     'rest_framework.permissions.IsAuthenticated',
        # ],
    }

     

  • 认证(Authentication)
    DRF也提供了多种认证类,用于验证用户的身份。常用的认证类包括:

    SessionAuthentication:使用Django的session机制进行认证,适用于web应用。
    TokenAuthentication:使用token进行认证,适用于移动应用等无状态应用。
    BasicAuthentication:使用HTTP基本认证进行认证。
    JSONWebTokenAuthentication:使用JSON Web Token进行认证,支持跨域认证。

  • 认证和自定义认证
  • from django.contrib.auth import get_user_model
    from rest_framework.authentication import BaseAuthentication
    
    
    class CustomerDefinedAuthentication(BaseAuthentication):
        def authenticate(self, request):
            """自定义认证方法:名字必须为 authenticate"""
            user = request.query_params.get("user")  # 获取请求参数中的user参数
            pwd = request.query_params.get("pwd")  # 获取请求参数中的pwd参数
            if user != "root" or pwd != "root":
                return None
            # 获取当前系统中用户表对应的用户模型信息
            user = get_user_model().objects.first()
            return (user, None)

     

  • from django.shortcuts import render
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from rest_framework.authentication import SessionAuthentication, BaseAuthentication  # drf自带认证
    from Restful_api.authentication import CustomerDefinedAuthentication  # 导入我们自定义认证
    
    
    class HomeAPIView(APIView):
        # 使用内部认证组件,或者是自定义组件
        # authentication_classes = [SessionAuthentication, BaseAuthentication]
        # authentication_classes = [CustomerDefinedAuthentication]
    
        def get(self, request):
            """单独设置认证:session认证"""
            print(request.user)
            if request.user.id is None:
                return Response("未登录用户:游客")
            else:
                return Response(f"已登录用户{request.user}")

  • 权限(Permission)
    DRF提供了多种权限类,用于限制用户访问API的权限。常用的权限类包括:

    AllowAny:允许任何人访问API。
    IsAuthenticated:只允许已登录的用户访问API。
    IsAdminUser:只允许管理员用户访问API。
    IsAuthenticatedOrReadOnly:未登录用户只能查看API,已登录用户可以进行修改操作。
    DjangoModelPermissions:根据Django模型的权限进行控制,例如Django中的add、change、delete权限。
    DjangoObjectPermissions:根据Django模型实例的权限进行控制。

  • 权限和自定义权限
  • from rest_framework.permissions import BasePermission
    
    
    class IsOwner(BasePermission):
        """自定义权限可用于全局配置或者局部配置
            返回True 允许访问
        """
        message = "只有该对象创建者才有资格访问"
    
        def has_permission(self, request, view):
            """视图权限
            """
            role = request.query_params.get("role")
            return role == "one_name"
    
        def has_object_permission(self, request, view, obj):
            """模型权限"""
            return obj.owner == request.user

     

  •  

    class HomeAPIView(APIView):
        # authentication_classes = [SessionAuthentication, BaseAuthentication]#内部认证
        # authentication_classes = [CustomerDefinedAuthentication]#自定义认证
    
        # permission_classes = [IsRootPermission]#自定义权限
        permission_classes = [IsAuthenticated]  # 为空则取消权限的识别
    
        def get(self, request):
            """单独设置认证:session认证"""
            print(request.user)
            if request.user.id is None:
                return Response("未登录用户:游客")
            else:
                return Response(f"已登录用户{request.user}")

     

  • 目录解释:在主应用下创建 一下python文件 写自定义认证和权限的代码
  •  

     

  • 全局配置时导入方式:均一致,按照setting中导入即可
posted @ 2023-04-04 17:12  Hide_凉辰  阅读(21)  评论(0)    收藏  举报