I am working on a Django backend. The backend is deployed on Render, and I am testing email validation logic by sending OTP but for that i need to send “csrftoken” for the POST request.
views.py:
@ensure_csrf_cookie
def register(request):
if request.method == "POST":
......
elif request.method == "GET":
return JsonResponse({"message": "GET request handled"}, status=200)
prod.py:
from .common import *
CSRF_TRUSTED_ORIGINS = [
"http://127.0.0.1:8001",
"http://localhost:8001",
"https://forkmemaybe.github.io/temp/",
]
CSRF_COOKIE_SAMESITE = "None"
CSRF_COOKIE_SECURE = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
"http://127.0.0.1:8001",
"http://localhost:8001",
"https://forkmemaybe.github.io/temp/",
]
SESSION_COOKIE_SAMESITE = "None"
SESSION_COOKIE_SECURE = True
i tried reading the cookie but it kept turning up “null”, when i checked it under dev tools it was there. since “HttpOnly” is not set it could only be that the browser is restricting cross-site cookies.
So what i was thinking of doing is this:
make a URL that would get the cookie and return “csrftoken” in response header (since cookie cant be read cross site):
@ensure_csrf_cookie
@require_http_methods(['GET'])
def set_csrf_token(request):
response = JsonResponse({"message": "GET request handled"}, status=200)
response["X-CSRFToken"] = request.META.get("CSRF_COOKIE", "")
return response
Question is, is this a secure way ? Is there any other way to do this ?