You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何降低Django特定视图的认证粒度?仅验证POST请求

实现特定请求方法的认证粒度控制

当然可以做到,你可以通过重写APIView的get_authenticators()和get_permissions()方法,根据请求方法动态返回对应的认证和权限类:

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

class PartView(APIView):
    def get_authenticators(self):
        # 仅POST请求使用JWT认证
        if self.request.method == 'POST':
            return [JSONWebTokenAuthentication()]
        return []

    def get_permissions(self):
        # 仅POST请求要求用户已认证
        if self.request.method == 'POST':
            return [IsAuthenticated()]
        return []

    def get(self, request, *args, **kwargs):
        # GET请求无需认证,直接处理逻辑
        ...
    def post(self, request, *args, **kwargs): 
        # POST请求会先经过JWT认证和权限校验,再处理逻辑
        ...

原理说明

  • get_authenticators()方法决定当前请求使用的认证器列表,我们判断如果是POST请求就返回JWT认证器,否则返回空列表(不做认证)。
  • get_permissions()方法同理,仅POST请求要求用户已认证,其他请求跳过权限校验。

另外也可以用方法装饰器的方式实现,给GET方法单独指定空的认证和权限类:

from django.utils.decorators import method_decorator
from rest_framework.decorators import authentication_classes, permission_classes
from rest_framework.views import APIView
from rest_framework.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated

class PartView(APIView):
    # 默认配置给POST请求使用
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]

    @method_decorator(authentication_classes([]))
    @method_decorator(permission_classes([]))
    def get(self, request, *args, **kwargs):
        ...

    def post(self, request, *args, **kwargs): 
        ...

两种方法都能实现你的需求,重写类方法的方式更直观,适合需要对多个请求方法做不同控制的场景。

内容的提问来源于stack exchange,提问作者Ayeemba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 15:51:31