DRF的认证与权限功能

  • 认证

1.全局配置

在setting.py进行配置。

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        # 'rest_framework.authentication.BasicAuthentication',  # 基本认证:账号密码认证
        'rest_framework.authentication.SessionAuthentication',  # session 认证
    )
}

2.针对一个视图设置

from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.views import APIView

class ExampleView(APIView):
    authentication_classes = (SessionAuthentication, BasicAuthentication)
    ...
  • 使用方法

  • request.user
    • 认证通过: AbstractUser对象
    • 未认证通过: AnonymousUser对象
  • request.user.is_authenticated(): 是否认证/登录通过

  • 权限

权限控制可以限制用户对于视图的访问和对于具体数据对象的访问。

  • 在执行视图的dispatch()方法前,会先进行视图访问权限的判断
  • 在通过get_object()获取具体对象时,会进行对象访问权限的判断

  • 提供的权限

    • AllowAny 允许所有用户 (默认值,允许所有用户访问)
    • IsAuthenticated 仅通过认证的用户
    • IsAdminUser 仅管理员用户
    • IsAuthenticatedOrReadOnly 认证的用户可以完全操作,否则只能get读取
  • 无权限时两种可能的返回值:

    • 401 Unauthorized 未认证
    • 403 Permission Denied 权限被禁止

1.全局设置

在setting.py进行配置。

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        # 四个选项,AllowAny、IsAuthenticated、IsAdminUser、IsAuthenticatedOrReadOnly
        'rest_framework.permissions.IsAuthenticated',
    )
}

2.针对一个视图设置

from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView

class ExampleView(APIView):
    # 对于当前视图中的动作,必须登录后才能访问
    permission_classes = (IsAuthenticated,)
    ...
  • 自定义权限

在某些时候,需要要到自定义权限。例如一个视图里面有几个接口,查找全部部门查找一个部门修改一个部门。我们想针对修改一个部门这个接口设置权限。这时候需要自定义权限。

如需自定义权限,需继承rest_framework.permissions.BasePermission父类,并实现以下两个任何一个方法或全部

  • .has_permission(self, request, view)

    是否可以访问视图, view表示当前视图对象

  • .has_object_permission(self, request, view, obj)

    是否可以访问数据对象, view表示当前视图, obj为数据对象

具体操作如下:

class MyPermission(BasePermission):
    """自定义权限"""
    def has_permission(self, request, view):
        """用户未登录不能修改部门"""
        if view.action == 'update' and not request.user.is_authenticated():
            return False
        else:
            return True


class DepartmentViewSet(ListModelMixin,RetrieveModelMixin,UpdateModelMixin,GenericViewSet):

    # 使用自定义权限
    permission_classes = [MyPermission]

    queryset = Department.objects.all()
    serializer_class = DepartmentSerializer

猜你喜欢

转载自www.cnblogs.com/chichung/p/9944863.html