首页 > 解决方案 > 如何使页面的某些部分在 django 中未经身份验证?

问题描述

我有一个使用 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')

那么我该如何实现呢?

标签: pythondjangoauthentication

解决方案


authentication_classes您可以通过设置以及像permission_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')


推荐阅读