Search code examples
pythondjangogoogle-cloud-platformgoogle-cloud-rungoogle-cloud-build

Django - CSRF verification failed in Cloud Run


EDIT: I tried doing the tutorial again. It now works perfectly so I must have mistyped something in my last attempt

I am following this tutorial from Google codelabs. When trying to login to the admin panel, I am getting a CSRF verification failed.

The tutorial is about deploying a fresh empty django project to Cloud Run. There's already a provided settings.py and I tried replacing it with this block to no avail:

# SECURITY WARNING: It's recommended that you use this when
# running in production. The URL will be known once you first deploy
# to Cloud Run. This code takes the URL and converts it to both these settings formats.
CLOUDRUN_SERVICE_URL = env("CLOUDRUN_SERVICE_URL", default=None)
if CLOUDRUN_SERVICE_URL:
    ALLOWED_HOSTS = [urlparse(CLOUDRUN_SERVICE_URL).netloc]
    CSRF_TRUSTED_ORIGINS = ['https://django-cloudrun-yd43yjf7ya-uc.a.run.app']
    SECURE_SSL_REDIRECT = True
    SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
else:
    ALLOWED_HOSTS = ["*"]

I've also tried hardcoding the CLOUDRUN_SERVICE_URL to the url provided on deployment, https://django-cloudrun-yd43yjf7ya-uc.a.run.app but it didn't work. With and without the slash at the end.

Also did a sanity check by writing a simple hello world view to check if my changes are really getting through.


Solution

  • Make sure to follow step 9 of the tutorial closely. Set the CLOUDRUN_SERVICE_URL to your generated service URL.

    Retrieve the service URL:

    CLOUDRUN_SERVICE_URL=$(gcloud run services describe django-cloudrun \
      --platform managed \
      --region $REGION  \
      --format "value(status.url)")
    echo $CLOUDRUN_SERVICE_URL
    

    Set this value as an environment variable on your Cloud Run service:

    gcloud run services update django-cloudrun \
      --region $REGION \
      --update-env-vars CLOUDRUN_SERVICE_URL=$CLOUDRUN_SERVICE_URL