I've just started using Django Rest Framework, and I'm slightly confused about the usage of CSRF tokens in requests. For example, using a standard Django view with the below request would require a CSRF token:
fetch("http://127.0.0.1:8000/api/add_item/", {
method: "POST",
headers: {
"Content-Type": "application/json"
// "X-CSRFToken": Cookies.get("csrftoken")
},
body: JSON.stringify({ content: value })
})
But doesn't seem to with the below DRF implementation:
@api_view(['POST'])
def add_item(request):
serializer = ToDoSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
Is there a reason for this?
CodePudding user response:
DRF does not use the same underlying authentication as Django forms by default. No CSRF tokens are expected.
You must configure Authentication for DRF separately. For example, enabling session-based authentication you can set default auth classes in your settings.py
file:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
# ... add other auth methods here
]
}
Also note from the docs regarding CSRF tokens with session auth in DRF:
CSRF validation in REST framework works slightly differently from standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.