mac*_*ost 42 authentication django-rest-framework
我正在一个商店网站上工作,每个用户都将是匿名的(好吧,至少需要付费),我正在尝试使用Django REST Framework来提供产品API,但它一直在抱怨:
"detail": "Authentication credentials were not provided."
我发现了一些与身份验证相关的设置,但我找不到类似的东西ENABLE_AUTHENTICATION = True.如何简单地禁用身份验证,并让站点的任何访问者访问API?
ina*_*inc 49
REST_FRAMEWORK = {
    # other settings...
    'DEFAULT_AUTHENTICATION_CLASSES': [],
    'DEFAULT_PERMISSION_CLASSES': [],
}
Aas*_*oni 38
您还可以禁用特定类或方法的身份验证,只需保留特定方法的装饰器.
from rest_framework.decorators import authentication_classes, permission_classes
@api_view(['POST'])    
@authentication_classes([])
@permission_classes([])
def items(request):
   return Response({"message":"Hello world!"})
如果您想为某个基于类的视图禁用身份验证,那么您可以使用,
class PublicEndPoint(APIView):
    authentication_classes = [] #disables authentication
    permission_classes = [] #disables permission
    
    def get(self, request):
        pass
当您只想公开特定的端点时,这很有用。
小智 7
要全局启用身份验证,请将其添加到 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)
如果使用 APIView,您可以为视图创建权限,示例如下:
网址.py
url(r'^my-endpoint', views.MyEndpoint.as_view())
权限.py
class PublicEndpoint(permissions.BasePermission):
    def has_permission(self, request, view):
        return True
视图.py
from permissions import PublicEndpoint
class MyEndpoint(APIView):
    permission_classes = (PublicEndpoint,)
    def get(self, request, format=None):
        return Response({'Info':'Public Endpoint'})
您也可以通过将其应用于类或方法,将其应用于一个特定的端点。只需要将django rest框架的AllowAny权限应用于特定的方法或类。
views.py
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()
您可以通过为权限设置使用空列表或元组来获得相同的结果,但是您可能会发现指定此类非常有用,因为它使意图明确。
| 归档时间: | 
 | 
| 查看次数: | 29189 次 | 
| 最近记录: |