Search code examples
djangodjango-rest-frameworkdjango-generic-views

using django permissions.IsAuthenticatedOrReadOnly with token authentication


I have this Django API view that I want to allow authorized and unauthorized users access it, I have set Django token-authentication as the default authentication class, however, whenever I try to access the view as unauthenticated user,I get error Unauthorized: which is weird coz am making a get request in the view my code is here

@api_view(['GET'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly])
def all_Search(request):
    print(request.headers)
    src = request.GET.get('q')

my settings for rest framework is

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ]
}

is there a way to work around this? will appreciate any help, thanks


Solution

  • I've tried to reproduce your error but I failed. This is my configuration:

    settings.py

    INSTALLED_APPS = [
        ...
        'rest_framework',
        'rest_framework.authtoken'
    
    ]
    
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'rest_framework.authentication.TokenAuthentication',
            'rest_framework.authentication.SessionAuthentication',
        ]
    }
    

    urls.py

    urlpatterns = [
        path('search/', api.all_search, name="search")
    
    ]
    

    api.py

    from rest_framework import permissions
    from rest_framework.decorators import api_view, permission_classes
    from rest_framework.response import Response
    
    @api_view(['GET'])
    @permission_classes([permissions.IsAuthenticatedOrReadOnly])
    def all_Search(request):
        print(request.headers)
        src = request.GET.get('q')
        return Response()
    

    test.py

    from rest_framework import status
    from rest_framework.test import APILiveServerTestCase
    from rest_framework.reverse import reverse
    
    class TestTokenAuthorization(APILiveServerTestCase):
        def test_can_search_without_token(self):
            url = reverse('search', kwargs={})
            response = self.client.get(url, {}, format='json')
            self.assertEqual(response.status_code, status.HTTP_200_OK)
    

    and this is the result of the test:

    Creating test database for alias 'default'...
    System check identified no issues (0 silenced).
    {'Cookie': '', 'Content-Type': 'application/octet-stream'}
    Destroying test database for alias 'default'...
    

    I'm using djangorestframework==3.10.3 and python3.7

    As you can see, I didn't authenticate the request (no token is passed) and the headers were printed as expected from the permissions.

    Maybe your issue is caused by something else in your code. Try to include more details in your question.

    By the way, your all_Search function is missing the return Response()