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

Django REST框架视图指定权限未覆盖默认权限问题求助

问题解决方法

1. 调整装饰器顺序

函数视图的装饰器执行顺序是从下到上(靠近函数的装饰器先执行),@api_view需要先将普通函数转换为DRF的API视图,@permission_classes才能正确作用于这个API视图。确保你的装饰器顺序如下:

@requires_csrf_token
@permission_classes([IsAuthenticated])
@api_view(["POST"])
def logout(request):
    # 你的视图逻辑
    pass

如果还是不生效,可以先移除@requires_csrf_token测试权限是否正常,排除CSRF装饰器的干扰。

2. 确认JWT认证配置

确保在settings.py中正确配置了django-rest-simple-jwt的认证类,否则IsAuthenticated权限无法识别已登录用户:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ],
}

3. 备用方案:改用类视图

如果函数视图的装饰器问题仍无法解决,可以改用DRF的类视图,权限配置更直观且不易出错:

from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from django.views.decorators.csrf import requires_csrf_token
from django.utils.decorators import method_decorator

@method_decorator(requires_csrf_token, name='post')
class LogoutView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        # 你的视图逻辑
        pass

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 12:25:22