Django API unittest JWT аутентификация всегда 403 Forbidden
Я пытаюсь написать модульные тесты для моего Django API, который имеет JWT аутентификацию. Но каждый тест получает код состояния 403 - Forbidden. Я также пробовал использовать force_authenticate, но он не работает. Когда я работаю с Postman, все в порядке. Вот код ниже и один из тестов. Спасибо за помощь, если она есть.
test_view.py:
from rest_framework.test import APIClient, APITestCase
from django.urls import reverse
from users.models import User
class TestViews(APITestCase):
def setUp(self):
self.client = APIClient()
self.register_url = reverse('register')
self.login_url = reverse('login')
self.user_url = reverse('user')
self.logout_url = reverse('logout')
self.user1 = User.objects.create(
email = "petar@stripe.com",
first_name = "Petar",
last_name = "Petrovic",
password = "petar123"
)
self.user1 = User.objects.get(email="petar@stripe.com")
self.client.force_authenticate(user=self.user1)
self.data_login = {
"email": "petar@stripe.com",
"password": "petar123"
}
def test_login_POST(self):
response = self.client.post(self.login_url, data=self.data_login, format="json")
self.assertEquals(response.status_code, 200) # AssertionError: 403 != 200
self.assertTrue("jwt" in response.data) # AssertionError: False is not true
models.py:
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
email = models.EmailField(max_length=255, unique=True)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
password = models.CharField(max_length=255)
username = None
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
views.py:
from rest_framework.views import APIView
from RecipesAPI.constants import HUNTER_API_KEY, CLEARBIT_API_KEY, JWT_KEY
import requests
from rest_framework.response import Response
from rest_framework.exceptions import AuthenticationFailed, ValidationError
from .serializers import UserSerializer
from .models import User
import jwt, datetime
import clearbit
class LoginView(APIView):
def post(self, request):
email = request.data['email']
password = request.data['password']
user = User.objects.filter(email=email).first()
if user is None:
raise AuthenticationFailed('User not found!')
if not user.check_password(password):
raise AuthenticationFailed('Incorrect password!')
payload = {
'id': user.id,
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
'iat': datetime.datetime.utcnow()
}
token = jwt.encode(payload, JWT_KEY, algorithm='HS256').decode('utf-8')
response = Response()
response.set_cookie(key='jwt', value=token, httponly=True)
response.data = {
'jwt': token
}
return response