如何在 Django 中使页面的某些部分未经身份验证?

时间:2021-01-01 12:33:54

标签: python django authentication

我有一个使用 JWT 作为身份验证类的 Django 项目。但是对于我的应用程序的某些页面没有身份验证。但是当我提出请求时,它仍然返回以下内容。

{
    "detail": "You do not have permission to perform this action."
}

我的身份验证课程在这里

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

我的视图文件在这里

class Hello(APIView):
    authentication_classes = []
    def post(self, request):
        return Response('Hello')

那么我如何实现这个目标?

1 个答案:

答案 0 :(得分:1)

您可以通过将 authentication_classespermission_classes 设置为空列表来禁用/绕过身份验证,如下所示:

class Hello(APIView):
    authentication_classes = []
    permission_classes = []
    def post(self, request):
        return Response('Hello')

或者如果你想使用基于函数的方法,你可以使用装饰器来设置它们的值,如下所示:

from rest_framework.decorators import authentication_classes, permission_classes

@api_view(['POST'])    
@authentication_classes([])
@permission_classes([])
def hello(request):
   return Response('Hello')