Django REST Framework(十八)权限

为了更全面地了解如何在 Django REST framework 中配置权限和认证,我们将从以下几个部分详细介绍:

  1. 全局配置
  2. 自定义认证
  3. 自定义权限
  4. 视图中的应用
  5. 路由配置

1. 全局配置

settings.py 中,我们可以配置全局的认证和权限类,这样所有的视图都将默认使用这些设置。以下是一个详细的配置示例:

# settings.py

REST_FRAMEWORK = {
    # 全局认证配置
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',  # session 认证
        'rest_framework.authentication.BasicAuthentication',    # 基本认证
        'yourapp.authentications.CustomAuthentication',          # 自定义认证
    ),
    # 全局权限配置
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',           # 仅登录用户
    ),
}

2. 自定义认证

我们可以通过创建自定义认证类来实现项目特定的认证需求。以下是一个详细的自定义认证类示例:

# yourapp/authentications.py

from rest_framework.authentication import BaseAuthentication
from django.contrib.auth.models import User

class CustomAuthentication(BaseAuthentication):
    """
    自定义认证类
    """
    def authenticate(self, request):
        role = request.query_params.get("role")
        if role == "root":
            try:
                user = User.objects.get(pk=1)
                return (user, None)  # 返回格式必须是 (user, auth) 或 None
            except User.DoesNotExist:
                return None
        return None

3. 自定义权限

自定义权限类可以让你根据特定条件来控制访问权限。以下是一个详细的自定义权限类示例:

# yourapp/permissions.py

from rest_framework.permissions import BasePermission

class IsXiaoMingPermission(BasePermission):
    """
    自定义权限类
    """
    def has_permission(self, request, view):
        role = request.query_params.get("role")
        return role == "xiaoming"

    def has_object_permission(self, request, view, obj):
        return True

4. 视图中的应用

在视图中,你可以通过 authentication_classespermission_classes 属性来设置局部的认证和权限,这些设置会覆盖全局配置。以下是详细的视图示例:

# yourapp/views.py

from rest_framework.viewsets import ModelViewSet
from yourapp.models import Student
from yourapp.serializers import StudentSerializer
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated, IsAdminUser, IsAuthenticatedOrReadOnly
from yourapp.permissions import IsXiaoMingPermission
from yourapp.authentications import CustomAuthentication

class Student1ModelViewSet(ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer
    # 局部认证配置
    authentication_classes = [SessionAuthentication, CustomAuthentication]
    # 局部权限配置
    # permission_classes = [IsAuthenticated]  # 只要经过认证登录就可以访问
    # permission_classes = [IsAdminUser]  # 只要是站点管理员就可以访问
    # permission_classes = [IsAuthenticatedOrReadOnly]  # 登录用户可以访问视图的增删查改页面,未登录的游客只能查看数据,不能修改!
    permission_classes = [IsXiaoMingPermission]  # 自定义权限

5. 路由配置

最后,我们需要配置路由来连接视图。以下是详细的路由配置示例:

# yourapp/urls.py

from django.urls import path, include
from . import views
from rest_framework.routers import SimpleRouter

router = SimpleRouter()
router.register("stu1", views.Student1ModelViewSet)

urlpatterns = [
    path("", include(router.urls)),
]

其他视图和功能示例

为了更全面地展示权限和认证的应用,以下是一些额外的视图和功能示例:

# yourapp/views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny

class PublicView(APIView):
    """
    允许所有用户访问的公开视图
    """
    permission_classes = [AllowAny]

    def get(self, request):
        return Response({"message": "This is a public view"})

class AdminView(APIView):
    """
    仅允许管理员用户访问的视图
    """
    permission_classes = [IsAdminUser]

    def get(self, request):
        return Response({"message": "This is an admin-only view"})

class AuthenticatedOrReadOnlyView(APIView):
    """
    已登录用户可以进行增删改,未登录用户只能查看
    """
    permission_classes = [IsAuthenticatedOrReadOnly]

    def get(self, request):
        return Response({"message": "Read-only for unauthenticated users"})

    def post(self, request):
        return Response({"message": "Write allowed for authenticated users"})

总结

通过以上详细的示例,可以更好地理解如何在 Django REST framework 中配置和应用权限和认证。这包括全局配置、自定义认证和权限类、在视图中应用这些类以及配置路由。通过这种方式,你可以灵活地控制视图和模型对象的访问权限,提高应用的安全性和可维护性。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yjjpp2301

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值