django-ninja: [BUG] CSRF Fails with Django Auth
Describe the bug When using django_auth (SessionAuth), the CSRF check fails from the Swagger docs page. The login endpoint returns a 200 and seems to be successful. However, when calling the update profile endpoint, it returns a 403 and says the CSRF check failed. This is from a brand new project and the settings are all default.
api.py
from django.contrib.auth import get_user_model, authenticate, login as django_login
from ninja import Schema, Field, NinjaAPI
from django.shortcuts import HttpResponse
from ninja.security import django_auth
from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie
api = NinjaAPI(csrf=True, auth=None)
UserModel = get_user_model()
class UserIn(Schema):
email: str = Field(..., pattern=r'^\S+@\S+\.\S+$')
password: str = Field(..., min_length=8)
@api.post('/login/', response={200: str, 401: str})
@csrf_exempt
@ensure_csrf_cookie
def login(request, user_in: UserIn):
user = authenticate(request, username=user_in.email, password=user_in.password)
if user is not None:
django_login(request, user)
return HttpResponse('Login successful', status=200)
else:
return 401, 'Invalid login'
class UserProfileIn(Schema):
first_name: str
last_name: str
class UserProfileOut(Schema):
email: str
first_name: str
last_name: str
@api.post('/profile/', auth=django_auth, response=UserProfileOut)
def update_profile(request, payload: UserProfileIn):
for attr, value in payload.dict().items():
setattr(request.user, attr, value)
request.user.save()
return request.user
Versions (please complete the following information):
- Python version: 3.10.11
- Django version: 4.2.10
- Django-Ninja version: 1.1.0
- Pydantic version: 2.6.3
About this issue
- Original URL
- State: open
- Created 3 years ago
- Comments: 16
This issue is because
APIKeyCookiewhichSessionAuthinherits from fordjango_authdefaults tocsrf = Trueeven if the NinjaAPI has CSRF off.I fixed it with a custom
django_authI guess when using
APIKeyCookie, CSRF On is best for security? However, for session auth that is not always the case because session auth has several mechanisms. Maybe there should be a setting to tweak CSRF on or off for SessionAuth?This is how we solved the issue as well, switch to JWT or another type of auth that doesn’t rely on CSRF checks. But that isn’t really a solution to the problem, but a work around.
To add on, I’ve figured out a workaround for this issue. It seems like the value contained in the X-CSRFToken header is incorrect when the request is coming from the Swagger docs. I wrote a middleware to take the unencrypted cookie value and replace the X-CSRFToken header with that value instead. That allows the request to go through and pass the CSRF check.