在Django 4.2 POST请求中获得403 Forbidden消息,即使包含CSRF令牌

xqnpmsa8  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(120)

我试图在网站中执行语言切换功能,我使用Django 4.2,并在根级别www.example.com文件中使用Django的i18n库。urls.py file.

urlpatterns = [
    path('i18n/', include('django.conf.urls.i18n')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += i18n_patterns(
    path('',apiView.WebsiteHomepageTemplate.as_view(),name="url_homepage_template"),
)

在模板文件中,我像这样执行语言切换:

<ul class="dropdown-menu" role="menu" id="language-list">
                  <li class="" id="language-switcher">
                    <form action="{% url 'set_language' %}" method="post" name="lang_form">
                      {% csrf_token %}
                      <input name="next" type="hidden" value="/" />
  
                      <select class="selectpicker" id="select_pickr" name="language">
                        {% get_available_languages as LANGUAGES %}
                        {% get_language_info_list for LANGUAGES as languages %}
                        {% for language in languages %}
  
                        <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected="selected" 
                        {%endif %} data-content='{{ language.code }}}'>
                          {% if language.code == 'en' %}
                          English
                          {% else %}
                          हिंदी
                          {% endif %}
  
                        </option>
  
                        {% endfor %}
                      </select>
                    </form>
                  </li>
                </ul>
    • 切换时,收到403禁止消息**

    • 当我使用开发工具检查时,我可以看到只有2个cookie正在使用,csrftoken和主题(用于更改亮暗模式)直到此刻**

因此,如果我在自定义403错误页面上再次执行切换,我可以切换到其他语言,并且在检查时可以看到langcookie存在。
当我从一个私人窗口这样做时,同样的事情不断发生。它至少在显示403消息后工作。

我还可以看到在请求头中我的csrftoken存在。
在我的服务器上,我在日志中收到以下消息:* * 禁止(CSRF cookie未设置。):/i18n/setlang/**
我的一些设置,我应用到使这个网站的安全:

DEBUG = False
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.middleware.locale.LocaleMiddleware',# for multi language 
    'django.contrib.sessions.middleware.SessionMiddleware',
    # ...caching
    'django.middleware.cache.UpdateCacheMiddleware',   
    'corsheaders.middleware.CorsMiddleware', # new   
    'django.middleware.common.CommonMiddleware',  
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # ...caching
    # 'django.middleware.cache.FetchFromCacheMiddleware',      
    'csp.middleware.CSPMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',  
    'silk.middleware.SilkyMiddleware',  
    'axes.middleware.AxesMiddleware',    
]

AUTHENTICATION_BACKENDS = [
    # AxesStandaloneBackend should be the first backend in the AUTHENTICATION_BACKENDS list.
    'axes.backends.AxesStandaloneBackend',

    # Django ModelBackend is the default authentication backend.
    'django.contrib.auth.backends.ModelBackend',
]


X_FRAME_OPTIONS = 'DENY'
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_HSTS_SECONDS = 86400
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
CSRF_TRUSTED_ORIGINS = ['https://*.mywebsite.com']
SECURE_BROWSER_XSS_FILTER = True
SESSION_COOKIE_HTTPONLY = True




CSP_DEFAULT_SRC = ("'self'","mywebsite.com","ajax.googleapis.com" )
CSP_SCRIPT_SRC = (
    "'self'",
    "https://www.googletagmanager.com",
    "fonts.googleapis.com",
    "mywebsite.com",
    'https://www.google.com/recaptcha/',
    'https://www.gstatic.com/recaptcha/',
    'https://www.youtube.com/embed/',
    'https://cdnjs.cloudflare.com/ajax/libs/tiny-slider/2.9.2/min/tiny-slider.js',
    "https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js",
    # "'strict-dynamic'"
    # "'unsafe-inline'"
)
CSP_FONT_SRC = ("'self'", "fonts.googleapis.com","fonts.gstatic.com")    
CSP_STYLE_SRC = [
    "'self'",
    "mywebsite.com",
    "fonts.googleapis.com",
    "'unsafe-inline'"

]  
CSP_IMG_SRC = ("'self'",'mywebsite.com','data:','blob:')
CSP_FRAME_SRC =(
    "'self'", 
    'https://www.google.com/recaptcha/', 
    'https://recaptcha.google.com/recaptcha/',
    'https://www.youtube.com/',
    "https://www.google.com/maps/"
) 
CORS_ALLOWED_ORIGINS = [
    "https://mywebsite.com" ,
]

#CONTENT SECURITY POLICY
CSP_CONNECT_SRC =("'self'","https://www.google-analytics.com/")
# CSP_OBJECT_SRC = ("'self'", 'mywebsite.com')
CSP_BASE_URI = ("'self'", )
CSP_FRAME_ANCESTORS = ("'self'","https://www.google.com/" )
CSP_FORM_ACTION = ("'self'", )
CSP_MANIFEST_SRC = ("'self'", )
CSP_WORKER_SRC = ("'self'", )
CSP_MEDIA_SRC = ("'self'", )
CSP_CHILD_SRC = ("'self'", )    
CSP_FORM_ACTION = ("'self'","mywebsite.com")
# CSP_STYLE_SRC = ("'self'","mywebsite.com",)
CSP_INCLUDE_NONCE_IN = [
    'default-src',
    'script-src',
    # 'style-src',
]
CSP_OBJECT_SRC = ("'self'","mywebsite.com")

请帮助我解决它。
先谢了

olmpazwi

olmpazwi1#

添加一行url白色名单settings.py

CSRF_TRUSTED_ORIGINS = ["https://mywebsite.com"]

相关问题