I'm using Django Rest Framework 3 and would like to test the CSRF verification.
First, I initialize the DRF APIClient
:
client = APIClient(enforce_csrf_checks=True)
Then I set a password on a user so I can login and get a session:
superuser.set_password('1234')
superuser.save()
client.login(email=superuser.email, password='1234')
Now we need a CSRF token. For that I simply create a request and retrieve the token from the cookies.
response = client.request()
csrftoken = client.cookies['csrftoken'].value
When inspecting the code, this seems to work, I get back a valid looking CSRF token. I then do the POST request, passing in the csrfmiddlewartoken
parameter:
data = {'name': 'My fancy test report', 'csrfmiddlewaretoken': csrftoken}
response = client.post(API_BASE + '/reports', data=data, format='json')
assert response.status_code == status.HTTP_201_CREATED, response.content
The problem is, this fails:
tests/api/test_api.py:156: in test_csrf_success
assert response.status_code == status.HTTP_201_CREATED, response.content
E AssertionError: {"detail":"CSRF Failed: CSRF token missing or incorrect."}
E assert 403 == 201
E + where 403 = <rest_framework.response.Response object at 0x7f7bd6453bd0>.status_code
E + and 201 = status.HTTP_201_CREATED
What's the correct way to test CSRF verification with DRF?