How Can I Disable Authentication in Django REST Framework

DjangoAuthenticationDjango Rest-Framework

Django Problem Overview


I'm working on a store site, where every user is going to be anonymous (well, until it's time to pay at least), and I'm trying to use Django REST Framework to serve the product API, but it keeps complaining about:

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

I found some settings related to authentication, but I couldn't find anything like ENABLE_AUTHENTICATION = True. How do I simply disable authentication, and let any visitor to the site access the API?

Django Solutions


Solution 1 - Django

You can give empty defaults for the permission and authentication classes in your settings.

REST_FRAMEWORK = {
    # other settings...

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

Solution 2 - Django

You can also disable authentication for particular class or method, just keep blank the decorators for the particular method.

from rest_framework.decorators import authentication_classes, permission_classes

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

Solution 3 - Django

if you want to disable authentication for a certain class based view, then you can use,

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

This is useful when you want to make only specific endpoints available public.

Solution 4 - Django

You can also apply it on one specific endpoint by applying it on class or method. Just need to apply django rest framework AllowAny permission to the specific method or class.

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()

You can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit.

Solution 5 - Django

To enable authentication globally add this to your django settings file:

'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.IsAuthenticated',
),

then add the following decorators to your methods to enable unauthenticated access to it

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)

Solution 6 - Django

If using APIView you can create a permission for the view, example below:

urls.py

url(r'^my-endpoint', views.MyEndpoint.as_view())

permissions.py

class PublicEndpoint(permissions.BasePermission):
    def has_permission(self, request, view):
        return True

views.py

from permissions import PublicEndpoint

class MyEndpoint(APIView):
    
    permission_classes = (PublicEndpoint,)

    def get(self, request, format=None):
        return Response({'Info':'Public Endpoint'})

Solution 7 - Django

Here is an alternative to simply enable the API forms for development purposes:

settings.py

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny'
    ]
}

Django REST framework v3.11.0

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmachineghostView Question on Stackoverflow
Solution 1 - DjangoinancsevincView Answer on Stackoverflow
Solution 2 - DjangoAashish SoniView Answer on Stackoverflow
Solution 3 - DjangoSumithranView Answer on Stackoverflow
Solution 4 - DjangoUmar AsgharView Answer on Stackoverflow
Solution 5 - DjangoRiley DavidsonView Answer on Stackoverflow
Solution 6 - DjangoSlipstreamView Answer on Stackoverflow
Solution 7 - DjangorbentoView Answer on Stackoverflow