简体   繁体   中英

Django app runs locally but I get CSRF verification failed on Heroku

My app runs fine at heroku local but after deployed to Heroku, every time I try to login/register/login as admin, it returns this error shown below.

I have tried to put @csrf_exempt on profile views, but that didn't fix the issue.

What can I do?

在此处输入图像描述

The error message is fairly self-explanatory (please excuse typos as I can't copy from an image):

Origin checking failed - https://pacific-coast-78888.herokuapp.com does not match any trusted origins

The domain you are using is not a trusted origin for CSRF.

There is then a link to the documentation, which I suspect goes to the Django CSRF documentation , though the documentation for the CSRF_TRUSTED_ORIGINS setting might be more useful:

A list of trusted origins for unsafe requests (eg POST ).

For requests that include the Origin header, Django's CSRF protection requires that header match the origin present in the Host header.

Look in your settings.py for CSRF_TRUSTED_ORIGINS and add https://pacific-coast-78888.herokuapp.com to the list. If that setting doesn't already exist, simply add it:

CSRF_TRUSTED_ORIGINS = ["https://pacific-coast-78888.herokuapp.com"]

If Heroku uses django "4.xx" version :

Then, if the error is as shown below:

Origin checking failed - https://example.com does not match any trusted origins.

Add this code below to "settings.py" :

CSRF_TRUSTED_ORIGINS = ['https://example.com']

In your case, you got this error:

Origin checking failed - https://pacific-coast-78888.herokuapp.com does not match any trusted origins.

So, you need to add this code below to your "settings.py" :

CSRF_TRUSTED_ORIGINS = ['https://pacific-coast-78888.herokuapp.com']

I was facing same error and simply downgraded my DjangoVersion==4.0.4 to DangoVersion==3.2.13. And it Work for me.

It appears you do not have your heroku address as a trusted origin in the setting.py file of your project, to do this, you can use corsheaders

pip install django-cors-headers 

then in your settings.py file

    INSTALLED_APPS = [ 
   ...
   'corsheaders',  
   ...
]

MIDDLEWARE = [
  'django.middleware.security.SecurityMiddleware',
  ...
  'django.middleware.clickjacking.XFrameOptionsMiddleware',
  'corsheaders.middleware.CorsMiddleware',
]

If you were not yet deployed you could add CORS_ORIGIN_ALLOW_ALL = True but because you know where your app is deployed using a whitelist for the origins is a much better idea

CORS_ORIGIN_WHITELIST = (
  'https://pacific-coast-78888.herokuapp.com',
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM