Complete worked example
python
from drf_lab import setup
setup()
from django.test import override_settings
from django.urls import path, clear_url_caches
from django.views.decorators.csrf import ensure_csrf_cookie
from rest_framework.authentication import SessionAuthentication
from rest_framework.decorators import api_view
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.test import APIClient
from rest_framework.views import APIView
from drf_lab import reset_fixture
@ensure_csrf_cookie
@api_view(["GET"])
def seed(request):
return Response({"ready": True})
class Change(APIView):
authentication_classes = [SessionAuthentication]
permission_classes = [IsAuthenticated]
def post(self, request):
return Response({"by": request.user.username, "accepted": True})
urlpatterns = [path("csrf/", seed), path("change/", Change.as_view())]
def inspect_example(payload):
alice, _, _ = reset_fixture()
client = APIClient(enforce_csrf_checks=True)
if payload.get("login", True):
client.force_login(alice)
with override_settings(ROOT_URLCONF=__name__):
clear_url_caches()
client.get("/csrf/")
headers = {"HTTP_X_CSRFTOKEN": client.cookies["csrftoken"].value} if payload.get("token") else {}
response = getattr(client, payload.get("method", "post"))("/change/", {}, format="json", **headers)
clear_url_caches()
return {"status": response.status_code, "body":
{"error": response.data["detail"].code} if response.status_code >= 400 else response.json()}- Reasoning
- Django SessionMiddleware and AuthenticationMiddleware resolve the session user. DRF SessionAuthentication enforces CSRF for the authenticated unsafe request. A valid cookie/token pair reaches the protected POST operation; omitting the header produces a permission failure. The seed route uses ensure_csrf_cookie so token acquisition is explicit. The helper does not force_authenticate the request, because doing so would bypass the session mechanism this topic needs to exercise. A logged-out request still fails the declared IsAuthenticated policy.