django CSRF_TRUSTED_ORIGINS not working as expected
Asked Answered
L

2

13

Im having trouble in understanding why a post from a third party site is being rejected even though the site is added to CSRF_TRUSTED_ORIGINS list in settings.py. Im receiving a 403 error after the post stating the the csrf check has failed. I thought that adding the site to CSRF_TRUSTED_ORIGINS should make the site exempt from csrf checks. Is there something else I should have done in order to receive post requests from external origins? Im running django 3.2

CSRF_TRUSTED_ORIGINS = ['site.lv']

request headers:

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,lv;q=0.8,ru;q=0.7
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 899
Content-Type: application/x-www-form-urlencoded
Host: cvcentrs-staging.herokuapp.com
Origin: https://www.site.lv
Pragma: no-cache
Referer: https://www.site.lv/
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Microsoft Edge";v="96"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: cross-site
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62
Lammond answered 28/12, 2021 at 14:39 Comment(0)
R
32

This assumption is wrong:

I thought that adding the site to CSRF_TRUSTED_ORIGINS should make the site exempt from csrf checks.

Adding the URL to CSRF_TRUSTED_ORIGINS is only one thing you need to do to allow a POST request from a form on an external domain. You also need to:

Starting from Django 4.0, you have to include the scheme in CSRF_TRUSTED_ORIGINS:

CSRF_TRUSTED_ORIGINS = ['https://site.lv', 'https://www.site.lv']
Rolling answered 29/12, 2021 at 10:39 Comment(0)
P
7

In order to enable CSRF_TRUSTED_ORIGINS follow these steps

  1. pip install django-cors-headers

installed apps

  1. INSTALLED_APPS = [ 'corsheaders', ]

middleware

  1. MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ]

make sure to add https

  1. CSRF_TRUSTED_ORIGINS = ['https://site.lv']

  2. if it still doesn't work, add this decorator to your views before function

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt 
def login(): pass
Pola answered 23/12, 2022 at 14:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.