Home > OS >  Authentication error 401 for jwt token in DRF tests
Authentication error 401 for jwt token in DRF tests

Time:06-23

I have a problem getting jwt authorization for get method in test. my tests:

class ImageViewsTests(APITestCase):
def setUp(self):
    self.test_user = User.objects.create_user(**TEST_USER)
    TEST_IMAGE['created_by'] = self.test_user
    self.temp_image = Image.objects.create(**TEST_IMAGE)
    self.token = RefreshToken.for_user(self.test_user)
    
    
def test_images_list(self):
    url = reverse('jwt-create')

    client = APIClient()
    client.credentials(HTTP_AUTHORIZATION=f'JWT {self.token.access_token}')
    response = self.client.get('/image/', data={'format': 'json'})
    
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.assertEqual(response.data, TEST_IMAGE)

Tests return AssertionError: 401 != 200. Token is returned correctly but does not work in header. For example everything is fine in Postman. postman

I did something else like this and I also get no authorization

def test_images_list(self):
    url = reverse('jwt-create')

    client = APIClient()
    resp = self.client.post(url, {'email':TEST_USER['email'], 'password':TEST_USER['password']}, format='json')
    
    self.assertEqual(resp.status_code, status.HTTP_200_OK)
    
    client.credentials(AUTHORIZATION=f'JWT {resp.data["access"]}')
    
    response = self.client.get('/image/', data={'format': 'json'})
    
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.assertEqual(response.data, TEST_IMAGE)

Im using Djoser, jwt, DRF. Where am I making a mistake?

CodePudding user response:

Try this for setting the credentials:

self.token = RefreshToken.for_user(self.test_user)
client.credentials(HTTP_AUTHORIZATION=f'Bearer {self.token.access_token}')
  • Related