Django + React on GPC Cloud Run, post request comes back with a 403 error
I'm attempting to submit a post request for a payment with Stripe. Despite trying many solutions on stackoverflow / reccomendations from CGPT my axios post request is still getting 403 blocked.
I'm using a react frontend and a Django backend.
I have a view get_csrf view looks like this.
def get_csrf(request): return JsonResponse({"csrf_token": get_token(request)})
My react frontend has the following:
axios.defaults.withCredentials = true;
const csrf = await axios.get("https://##########################.run.app/api/get-csrf");
const csrfToken = csrf.data['csrf_token'];
axios.defaults.headers.common['X-CSRFToken'] = csrfToken;
Cookies.set('csrftoken', csrfToken);
document.cookie shows there is a csrfcookie set.
The request shows that X-CSRFToken
and withCredentials
are set.
When submitting the from axios comes back with a 403 response.
GCP logs report: Forbidden (CSRF cookie not set.): /api/create-payment-intent/
My django settings contain the following:
CSRF_TRUSTED_ORIGINS = [
"https://owenmitchell.github.io",
'http://localhost:3000',
"http://127.0.0.1:3000"]
CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_DOMAIN = 'owenmitchell.github.io'
The reactfrontend is setup as a github pages with the above domain name.
My CORS settings are:
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000", # Frontend URL
"https://owenmitchell.github.io",
"http://127.0.0.1:3000",
]
CORS_ALLOW_METHODS = [
"GET",
"POST",
"PUT",
"PATCH",
"DELETE",
"OPTIONS",
]
I have django-cors-headers installed, 'corsheaders' is in my installed apps, and the cors middleware is in my middleware at the top.
The post works when I add the csrf_exempt decorator to the view, but as the post request is handling payments bypassing the security seems like a bad idea to me.
Thanks in advance for any help you can offer me.