Authentication 如何在Django REST框架中禁用身份验证

Authentication 如何在Django REST框架中禁用身份验证,authentication,django-rest-framework,Authentication,Django Rest Framework,我在一个商店网站上工作,那里的每个用户都是匿名的(好吧,至少在该付费之前),我试图使用Django REST Framework为产品API提供服务,但它一直在抱怨: "detail": "Authentication credentials were not provided." 我找到了一些与身份验证相关的设置,但找不到类似ENABLE\u authentication=True的设置。如何简单地禁用身份验证,并允许站点的任何访问者访问API?您可以在设置中为和类提供空的默认值 REST_

我在一个商店网站上工作,那里的每个用户都是匿名的(好吧,至少在该付费之前),我试图使用Django REST Framework为产品API提供服务,但它一直在抱怨:

"detail": "Authentication credentials were not provided."

我找到了一些与身份验证相关的设置,但找不到类似
ENABLE\u authentication=True
的设置。如何简单地禁用身份验证,并允许站点的任何访问者访问API?

您可以在设置中为和类提供空的默认值

REST_FRAMEWORK = {
    # other settings...

    'DEFAULT_AUTHENTICATION_CLASSES': [],
    'DEFAULT_PERMISSION_CLASSES': [],
}

您还可以禁用特定类或方法的身份验证,只需将特定方法的装饰符保留为空即可

from rest_framework.decorators import authentication_classes, permission_classes

@api_view(['POST'])    
@authentication_classes([])
@permission_classes([])
def items(request):
   return Response({"message":"Hello world!"})

如果使用APIView,则可以为该视图创建权限,示例如下:

url.py

url(r'^my-endpoint', views.MyEndpoint.as_view())
class PublicEndpoint(permissions.BasePermission):
    def has_permission(self, request, view):
        return True
from permissions import PublicEndpoint

class MyEndpoint(APIView):

    permission_classes = (PublicEndpoint,)

    def get(self, request, format=None):
        return Response({'Info':'Public Endpoint'})
from rest_framework.permissions import AllowAny

from .serializers import CategorySerializer
from catalogue.models import Category   

@permission_classes((AllowAny, ))
class CategoryList(generics.ListAPIView):
    serializer_class = serializers.CategorySerializer
    queryset = Category.objects.all()
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny'
    ]
}
权限。py

url(r'^my-endpoint', views.MyEndpoint.as_view())
class PublicEndpoint(permissions.BasePermission):
    def has_permission(self, request, view):
        return True
from permissions import PublicEndpoint

class MyEndpoint(APIView):

    permission_classes = (PublicEndpoint,)

    def get(self, request, format=None):
        return Response({'Info':'Public Endpoint'})
from rest_framework.permissions import AllowAny

from .serializers import CategorySerializer
from catalogue.models import Category   

@permission_classes((AllowAny, ))
class CategoryList(generics.ListAPIView):
    serializer_class = serializers.CategorySerializer
    queryset = Category.objects.all()
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny'
    ]
}
视图.py

url(r'^my-endpoint', views.MyEndpoint.as_view())
class PublicEndpoint(permissions.BasePermission):
    def has_permission(self, request, view):
        return True
from permissions import PublicEndpoint

class MyEndpoint(APIView):

    permission_classes = (PublicEndpoint,)

    def get(self, request, format=None):
        return Response({'Info':'Public Endpoint'})
from rest_framework.permissions import AllowAny

from .serializers import CategorySerializer
from catalogue.models import Category   

@permission_classes((AllowAny, ))
class CategoryList(generics.ListAPIView):
    serializer_class = serializers.CategorySerializer
    queryset = Category.objects.all()
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny'
    ]
}

您还可以通过将其应用于类或方法,将其应用于一个特定端点。只需对特定的方法或类应用django rest framework AllowAny权限即可

视图.py

url(r'^my-endpoint', views.MyEndpoint.as_view())
class PublicEndpoint(permissions.BasePermission):
    def has_permission(self, request, view):
        return True
from permissions import PublicEndpoint

class MyEndpoint(APIView):

    permission_classes = (PublicEndpoint,)

    def get(self, request, format=None):
        return Response({'Info':'Public Endpoint'})
from rest_framework.permissions import AllowAny

from .serializers import CategorySerializer
from catalogue.models import Category   

@permission_classes((AllowAny, ))
class CategoryList(generics.ListAPIView):
    serializer_class = serializers.CategorySerializer
    queryset = Category.objects.all()
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny'
    ]
}

通过为权限设置使用空列表或元组,您可以获得相同的结果,但您可能会发现指定此类很有用,因为这样可以明确目的。

要全局启用身份验证,请将其添加到django设置文件中:

'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
),
然后将以下装饰器添加到方法中,以启用对它的未经身份验证的访问

from rest_framework.decorators import authentication_classes, permission_classes

@api_view(['POST'])
@authentication_classes([])
@permission_classes([])
def register(request):
  try:
    username = request.data['username']
    email = request.data['email']
    password = request.data['password']
    User.objects.create_user(username=username, email=email, password=password)
    return Response({ 'result': 'ok' })
  except Exception as e:
    raise APIException(e)

以下是一种简单地启用API表单进行开发的替代方法:

设置.py

url(r'^my-endpoint', views.MyEndpoint.as_view())
class PublicEndpoint(permissions.BasePermission):
    def has_permission(self, request, view):
        return True
from permissions import PublicEndpoint

class MyEndpoint(APIView):

    permission_classes = (PublicEndpoint,)

    def get(self, request, format=None):
        return Response({'Info':'Public Endpoint'})
from rest_framework.permissions import AllowAny

from .serializers import CategorySerializer
from catalogue.models import Category   

@permission_classes((AllowAny, ))
class CategoryList(generics.ListAPIView):
    serializer_class = serializers.CategorySerializer
    queryset = Category.objects.all()
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny'
    ]
}

Django REST framework v3.11.0

如果要禁用某个基于类的视图的身份验证,则可以使用

class PublicEndPoint(APIView):
    authentication_classes = [] #disables authentication
    permission_classes = [] #disables permission
    
    def get(self, request):
        pass

当您只想将特定端点公开时,这非常有用。

如何跳过中一个类的身份验证DRF@roanjain添加属性
authentication\u classes=[]
-正如其名称所示,设置dict只是一个默认值。@OllieFord这听起来像是一个灾难的配方。如果有人将默认身份验证设置为“无”,而后来另一个人忘记为任何端点指定任何身份验证类,则该端点将可能不受保护。我想继续使用“黑名单”而不是“白名单”,只为我想保持打开状态的特定端点指定一个神奇的匿名身份验证和权限类。@CsabaToth我不明白我上面的评论怎么不是你想要的?在设置中保留
'DEFAULT\u AUTHENTICATION\u CLASSES'=['YourAuthenticationClass']
,并将
AUTHENTICATION\u CLASSES=[]
放在要保持打开状态的视图上。如果未提供此属性,将使用“设置”中的默认值-此处无灾难。@CsabaToth我想您一定误读了我的建议-我不是说在“设置”中禁用授权,而是说在您希望无需授权即可访问的特定端点上覆盖它。我同意另一种选择(在设置中没有默认设置,在每个视图上都指定)是一场等待发生的噩梦。有没有人成功地实现了这个片段?我试过了,但没有工作。看这里:是的,在我的情况下,它工作得很好,我已经将它用于用户注册视图集,您能告诉我您遇到了什么错误吗?只有在使用
@api\u view
decorator:相关问题:您的PublicEndpoint实现与rest\u framework.permissions相同时,这才有效。AllowAny@MikePlacentra对这个完整的答案可以用from rest\u framework.permissions import AllowAny&permission\u classes=(AllowAny,)替换,它看起来非常有前途,而且最重要的是,它很容易理解!不幸的是,当我在我的代码库中使用它时,我仍然得到403禁止。我在
PublicEndpoint
中放置了一条日志语句,该日志语句未被命中,这意味着根本没有查询我的权限类:叹息:这就是路。非常感谢。谢谢,这对我有用