Search code examples
pythondjangodjango-rest-frameworkjwtdjango-tests

Django-rest-framework API test 403 {'detail': 'You do not have permission to perform this action.'}


I'm currently writing a test to test my get request, the get request require jwt access_token in the header which i'm using django-rest-framework-simplejwt to get the token as well as using it as default authentication class

settings.py:

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAdminUser',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
    # 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}

My test_api.py:

from rest_framework.test import APITestCase
from rest_framework import status
from rest_framework.test import APIClient 
from django.urls import reverse
from listing.models import Property
from backend.models import User

class PropertyTestCase(APITestCase):
    def setUp(self):
        property_1 = Property.objects.create(title="test", size=322.00, price=8000000, price_rent=300000, price_per_square_meter=500000, price_rent_per_square_meter=20000, description="description 1", type="sell", category="category 1", address="address 1", lat=21.027763, long=105.834160, images=["https://avatars2.githubusercontent.com/u/46511495?s=88&v=4"], contact_name="name 1", contact_address="test address 1", contact_phone="0923512213", contact_email="test@gmail.com", frontend=322, road=32, floor=4, bedroom=5, living_room=6, toilet=2, direction="Nam", balcony="Nam", meta_data={"menu": {"id": "file", "popup": {"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}]}, "value": "File"}})
        property_1.save()
        property_2 = Property.objects.create(title="test2", size=322.00, price=8000000, price_rent=300000, price_per_square_meter=500000, price_rent_per_square_meter=20000, description="description 2", type="rent", category="category 2", address="address 2", lat=21.027763, long=105.834160, images=["https://avatars2.githubusercontent.com/u/46511495?s=88&v=4"], contact_name="name 2", contact_address="test address 2", contact_phone="0923512213", contact_email="test2@gmail.com", frontend=322, road=32, floor=4, bedroom=5, living_room=6, toilet=2, direction="Nam", balcony="Nam", meta_data={"menu": {"id": "file", "popup": {"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}]}, "value": "File"}})
        property_2.save()
        self.property_1_id = property_1.id
        self.property_2_id = property_2.id
        self.client = APIClient()

        url = '/api/register'
        data = {
                "username": "dat12@icts.vn",
                "password": "123456",
                "confirm_password": "123456"
        }

        response = self.client.post(url, data=data, format='json')
        self.access_token = response.json()['data']['access']


    def test_list_property_success(self):
        url = '/api/property/'
        data = {
                "page": 1,
                "page_size": 2,
        }

        headers = {
            "Authorization": "Bearer {}".format(self.access_token)
        }
        self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.access_token)
        response = self.client.get(url, data=data, format='json', headers=headers)
        print(response.json())
        self.assertEqual(200, response.status_code)

I already tried the api in postman with the header Authorization and it worked, i also print the access token in the test and it's correct.

But when i run the test test_list_property_success current response with the code of 403 and the following response(print out in test)

{'detail': 'You do not have permission to perform this action.'}

I already set self.client.credentials and add headers in the get request, i don't know what else is missing.

Any help would be appreciate


Solution

  • Found out why because DEFAULT_PERMISSION_CLASSES is set as admin user so only admin role's token can be use in my api so i changed to :

    REST_FRAMEWORK = {
        # Use Django's standard `django.contrib.auth` permissions,
        # or allow read-only access for unauthenticated users.
        'DEFAULT_PERMISSION_CLASSES': [
            'rest_framework.permissions.IsAuthenticated',
        ],
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework_simplejwt.authentication.JWTAuthentication',
        ),
        # 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
    }
    

    and now it worked