Django DRF中IsAuthenticated权限类未生效问题求助
解决思路:DRF IsAuthenticated权限类未生效问题
问题根源:你将
permission_classes定义在了list方法内部,DRF不会识别方法内的权限配置,它只会读取类级别的permission_classes属性。因此即使你声明了IsAuthenticated,权限校验逻辑根本没触发,匿名请求自然能进入方法执行。修正方案:把
permission_classes移到类的顶层作为类属性,同时DRF会自动处理序列化数据的响应,无需手动调用JSONRenderer,可以简化代码:
class UserViewSet(viewsets.ViewSet): permission_classes = [IsAuthenticated] # 类级别配置权限 def list(self, request): print(request.user.is_authenticated, file=sys.stderr) u_serializer = GetUserSerializer(request.user) return Response(u_serializer.data, status=200)
- 进阶扩展:如果需要给不同方法设置不同权限,可使用
action装饰器单独指定:
from rest_framework.decorators import action from rest_framework.permissions import AllowAny class UserViewSet(viewsets.ViewSet): # 类默认权限 permission_classes = [IsAuthenticated] def list(self, request): # 继承类权限 ... @action(detail=False, permission_classes=[AllowAny]) def public_info(self, request): # 该方法允许匿名访问 ...
内容的提问来源于stack exchange,提问作者Ethan G.
相关产品推荐
相关产品推荐

