Gem
Gem

Reputation: 545

Django - Default Authentication Allowany is not working

Here I am using django with default authentication. My authentication class in settings.py is

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
            'rest_framework.permissions.IsAuthenticated',
        ],
}

I set it as a default authentication

but for some API, I don't need Authentication at that time I use allow any but it is not working it required Token like

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

My code for POST method is

class EnquiryCrudPost(APIView):
    def post(self, request):
        UserData = request.data
        authentication_classes = (TokenAuthentication)
        permission_classes = (AllowAny)
        if UserData:
            try:
                NewUserData = Enquiry.objects.create()
                ..........

Thank you

Upvotes: 1

Views: 2739

Answers (2)

adist98
adist98

Reputation: 49

As mentioned by @JPG, since you have a class based view, you need to define your permission classes and authentication classes outside your method. Also AllowAny comes under permission_classes and not under authentication_classes.

In case you had a function based view, you could use a decorator outside the function definition like so

from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

@api_view(['GET'])
@permission_classes([AllowAny])
def example_view(request, format=None):
    content = {
        'status': 'request was permitted'
    }
    return Response(content)

Here's some documentation that'll help you understand permission and authentication classes better https://www.django-rest-framework.org/api-guide/permissions/#object-level-permissions

Upvotes: 1

JPG
JPG

Reputation: 88659

The authentication_classes and permission_classes should be defined as class attributes, not within your method. Also, it should be list or tuple

class EnquiryCrudPost(APIView):
    authentication_classes = (TokenAuthentication,) # you were missing a comma
    permission_classes = (AllowAny,)# you were missing a comma

    def post(self, request):
        ...

In this particular case, the authentication_classes is not really matter since you wish to use the AllowAny

Upvotes: 3

Related Questions