【问题标题】:how to make some part of the page as unauthenticated in django?如何使页面的某些部分在 django 中未经身份验证?
【发布时间】:2021-01-01 12:33:54
【问题描述】:

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

那么我该如何实现这个东西呢?

【问题讨论】:

  • 您可以尝试设置permission_classes = [AllowAny] 而不是authentication_classes。通过从rest_framework.permissions 导入AllowAny
  • 确实如此。刚才我想通了!总之谢谢!!!

标签: python django authentication


【解决方案1】:

您可以通过将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')

【讨论】:

  • 因为我使用基于类的视图。如果您有基于类的视图的代码,请更新它。我会接受
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-21
  • 1970-01-01
  • 2010-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多