I am having strange behaviour regarding the setting of a CSRF cookie by Django in Postman & Chrome and with different settings:
Situation 1:
I set 'django.middleware.csrf.CsrfViewMiddleware' in my MIDDLEWARE settings.
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
I do a POST call with Postman to a REST endpoint:
class BlogCreateView(APIView):
http_method_names = ['post']
def get_context_data(self, **kwargs):
return {
'request': self.request,
'kwargs': kwargs,
}
def post(self, request, **kwargs):
"""
POST a new object
"""
context = self.get_context_data(**kwargs)
serializer = self.serializer(data=request.data, context=context)
serializer.is_valid(raise_exception=True)
new_instance = serializer.save()
return Response(serializer.data, status=HTTP_201_CREATED)
The CSRF cookie is not set. I don't set a csrf value in the header of the request either. But the server accepts it. This should not happen right?
Situation 2:
When i simply go to http://localhost:8000/blogs/create in my Chrome browser. This makes a GET request to the same endpoint. The response is "detail": "Method \"GET\" not allowed." which is expected. But the cookie IS set in the browser.
Situation 3:
I turn off CsrfViewMiddleware
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
And I do a POST call to my Graphene endpoint with Postman:
from graphene_django.views import GraphQLView
urlpatterns = [
path('graphql', GraphQLView.as_view(graphiql=True)),
]
And now the cookie is set in Postman! This combination of situations makes no sense to me. Help would be much appreciated.
My goal is to have csrf protection working for production eventually. But I would like to test it locally.